+-
Python Pandas:Groupby Sum和Concatenate字符串
示例Pandas Dataframe:

ID Name COMMENT1 COMMENT2 NUM
1  dan  hi       hello    1
1  dan  you      friend   2
3  jon  yeah     nope     3
2  jon  dog      cat      .5
3  jon  yes      no       .1

我正在尝试创建一个按ID和NAME分组的数据框,它连接COMMENT1和COMMENT2,它们也总和了NUM.

这就是我要找的东西:

ID Name COMMENT1     COMMENT2        NUM
1  dan  hi you       hello friend    3
3  jon  yeah yes     nope no         3.1
2  jon  dog          cat             .5

我试过用这个:

input_df = input_df.groupby(['ID', 'NAME', 'COMMENT1', 'COMMENT2']).sum().reset_index()

但它不起作用.

如果我用这个:

input_df = input_df.groupby(['ID']).sum().reset_index()

它将NUM列相加,但不包括所有其他列.

最佳答案
让我们把它变成一条线

df.groupby(['ID','Name'],as_index=False).agg(lambda x : x.sum() if x.dtype=='float64' else ' '.join(x))
Out[1510]: 
   ID Name  COMMENT1      COMMENT2  NUM
0   1  dan    hi you  hello friend  3.0
1   2  jon       dog           cat  0.5
2   3  jon  yeah yes       nope no  3.1
点击查看更多相关文章

转载注明原文:Python Pandas:Groupby Sum和Concatenate字符串 - 乐贴网