gpt4 book ai didi

python Pandas : Groupby Sum AND Concatenate Strings

转载 作者:太空狗 更新时间:2023-10-30 01:56:52 25 4
gpt4 key购买 nike

示例 Pandas 数据框:

ID Name COMMENT1 COMMENT2 NUM1  dan  hi       hello    11  dan  you      friend   23  jon  yeah     nope     32  jon  dog      cat      .53  jon  yes      no       .1

I am trying to create a dataframe that groups by ID and NAME that concatenates COMMENT1 and COMMENT2 that also sums NUM.

This is what I'm looking for:

ID Name COMMENT1     COMMENT2        NUM1  dan  hi you       hello friend    33  jon  yeah yes     nope no         3.12  jon  dog          cat             .5

I tried using this:

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 AND Concatenate Strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47600818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com