python - 使用 .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 之后的所有列,或者有什么方法可以改进我的解决方案?
解决方案
您可以为所有列值创建字典动态,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
推荐阅读
- java - 使用 Flink 时,字数总是在变化
- python - 如何安装旧版本的 Tensorflow?
- c# - 如何在 Windows 10 中获得默认的强调色?
- javascript - 使用 Map Function 编写 React 组件时,对象作为 React Child 无效
- angular - 带按钮的角度拖放列表
- angularjs - 在窗口弹出窗口中打开时,ckd-overlay-container 不起作用
- ruby-on-rails - Rails 6 国际化 - 发生了什么变化?
- android - 如何在这两个表之间创建链接?
- python - 为什么 HTML 与我检查元素时的不同?
- pip - 如何修复 ModuleNotFoundError:没有名为“pyjokes”的模块