首页 > 解决方案 > 使用 .agg(多列)使 groupby 之后的所有列更有效

问题描述

我发现了一些与此问题相关的主题,“如何在 groupby 之后保留所有列”,但我的问题是,我知道如何,但我不知道如何更有效地做到这一点。

例子:

df=pd.DataFrame({'A':[1,1,2,3], 'B':[2,2,4,3],'d':[2,np.nan,1,4],'e':['this is','my life','not use 1','not use 2'],'f':[1,2,3,4]
                 })

print(df)
   A  B    d          e  f
0  1  2  2.0    this is  1
1  1  2  NaN    my life  2
2  2  4  1.0  not use 1  3
3  3  3  4.0  not use 2  4

e如果列A and B相等,我需要从列连接字符串。为此,我正在使用以下代码:

df=df.groupby(['A','B'],as_index=False).agg({'e':' '.join,'d':'first','f':'first'})
print(df)
   A  B    d  f                e
0  1  2  2.0  1  this is my life
1  2  4  1.0  3        not use 1
2  3  3  4.0  4        not use 2

这对我来说是正确的输出。但正如你所看到的,为了保留专栏,f and d我需要将它们agg dict一一放入其中。在我的真实数据中,我有 20 列,我不想在我的代码中手动输入所有这些列的名称。

有没有比我现在使用的更好的解决方案来保留 groupby 之后的所有列,或者有什么方法可以改进我的解决方案?

标签: pythonpandas

解决方案


您可以为所有列值创建字典动态,Index.difference排除dict.fromkeys字典的列表和方法,然后添加e到字典:

d = dict.fromkeys(df.columns.difference(['A','B','e']), 'first')
print(d)
{'d': 'first', 'f': 'first'}

d['e'] = ' '.join
print(d)
{'d': 'first', 'f': 'first', 'e': <built-in method join of str object at 0x00000000025E1880>}

或者,您可以分别创建两个字典并将merge它们一起创建:

d1 = dict.fromkeys(df.columns.difference(['A','B','e']), 'first')
d2 = {'e': ' '.join}

d = {**d1, **d2}

df=df.groupby(['A','B'],as_index=False).agg(d)
print(df)
   A  B    d  f                e
0  1  2  2.0  1  this is my life
1  2  4  1.0  3        not use 1
2  3  3  4.0  4        not use 2

最后,如果订单很重要,则与原始添加相同DataFrame.reindex

df=df.groupby(['A','B'],as_index=False).agg(d).reindex(df.columns, axis=1)
print (df)
   A  B    d                e  f
0  1  2  2.0  this is my life  1
1  2  4  1.0        not use 1  3
2  3  3  4.0        not use 2  4

推荐阅读