我发现了一些与这个问题相关的主题,“如何在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
如果列 A 和 B
相等,我需要连接列 e
中的字符串。
为此,我使用以下代码:
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 和 d 列,我需要将它们一一放入这个 agg dict 中。 在我的真实数据中,我有 20 列,我不想在代码中手动输入所有这些列的名称。
是否有更好的解决方案来保留 groupby 之后的所有列, 或者有什么方法可以改进我的解决方案,而不是我现在使用的?
最佳答案
您可以使用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>}
或者您可以分别创建两个字典并将它们合并
在一起:
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
关于python - 使用 .agg(许多列)保留 groupby 之后的所有列更有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173437/