在相同值的情况下组合pandas数据帧单元

时间:2016-08-02 19:12:30

标签: python pandas

我试图创建一个新的数据框,如果是'类型'发生不止一次,“国家/地区”的内容细胞和'#year;'这些行的单元格组合在一行中(' how'列的行为类似于' type'列:如果类型相似,那么hows也是如此)。

我的pd数据框如下所示,df:

%~dp0

df2应如下所示:

xmlDoc.Save(String.Format(@"{0}\{1}2", settingsDir, settingsFilename));

我非常确定一个小组在'类型' (或类型和如何)是必要的。例如,使用first()删除第二个相似类型的行。是否有一些方便的方法来组合单元格(字符串)?提前谢谢。

2 个答案:

答案 0 :(得分:3)

groupby/agg', '.join一起用作聚合器:

import pandas as pd
df = pd.DataFrame({'country': ['UK', 'GER', 'USA', 'AUS', 'CAN', 'SA', 'RU'],
 'how': ['S', 'D', 'D', 'F', 'R', 'L', 'L'],
 'type': ['t1', 't2', 't2', 't3', 't4', 't5', 't5'],
 'year': ['2009', '2010', '2011', '2012', '2013', '2014', '2015']})

result = df.groupby(['type','how']).agg(', '.join).reset_index()

产量

  type how   country        year
0   t1   S        UK        2009
1   t2   D  GER, USA  2010, 2011
2   t3   F       AUS        2012
3   t4   R       CAN        2013
4   t5   L    SA, RU  2014, 2015

答案 1 :(得分:0)

获取每个单元格中的列表而不是字符串

def proc_df(df):
    df = df[['country', 'year']]
    return pd.Series(df.T.values.tolist(), df.columns)

df.groupby(['how', 'type']).apply(proc_df)

enter image description here

相关问题