python - pandas 使用 concat 基于单列添加和重命名多列
问题描述
我有这个df:
group owner failed granted_pe slots
0 g1 u1 0 single 1
1 g50 u92 0 shared 8
2 g50 u92 0 shared 1
df
可以使用以下代码创建:
df = pd.DataFrame([['g1', 'u1', 0, 'single', 1],
['g50', 'u92', '0', 'shared', '8'],
['g50', 'u92', '0', 'shared', '1']],
columns=['group', 'owner', 'failed','granted_pe', 'slots'])
df = (df.astype(dtype={'group':'str', 'owner':'str','failed':'int', 'granted_pe':'str', 'slots':'int'}))
print(df)
使用 groupby 我创建了在“slots”列上计算的三列:
df_calculated = pd.concat([
df.loc[:,['group', 'slots']].groupby(['group']).sum(),
df.loc[:,['group', 'slots']].groupby(['group']).mean(),
df.loc[:,['group', 'slots']].groupby(['group']).max()
], axis=1)
print(df_calculated)
slots slots slots
group
g1 1 1.0 1
g50 9 4.5 8
问题 1:适当命名新列
我可以向 concat 添加一个参数以将这些列命名为“slots_sum”、“slots_avg”和“slots_max”吗?
问题 2:将列添加到 df
我希望将新列添加到 df 的“源”列(在本例中为“槽”)右侧。所需的输出看起来像这样:
group owner failed granted_pe slots slots_sum slots_avg slots_max
0 g1 u1 0 single 1 1 1.0 1
1 g50 u92 0 shared 8 9 4.5 8
2 g50 u92 0 shared 1
我的实际 df 是 450 万行,23 列。我想为其他专栏做类似的事情。
解决方案
使用agg
with add_prefix
then merge
it back
yourdf=df.merge(df.groupby('group')['slots'].agg(['sum','mean','max']).add_prefix('slots_').reset_index(),how='left')
Out[86]:
group owner failed ... slots_sum slots_mean slots_max
0 g1 u1 0 ... 1 1.0 1
1 g50 u92 0 ... 9 4.5 8
2 g50 u92 0 ... 9 4.5 8
推荐阅读
- java - 在 Eclipse 链接 jpa 中移动到 java 8 时间后,derby 数据库中的错误
- jmeter - 在 1 个测试计划中执行许多测试
- r - 列 R 中有多个字符串的条件
- excel - 打开具有特定名称模式的不同文件夹和工作表?
- python - 从 xlsx 导入到 pandas 时带有“无”标题的列
- java - Spring Boot应用程序属性解密jpa密码
- c# - 开始日期保存到数据库,而不是 DataPicker 中选择的日期
- python - (熊猫)按一列分组,只保留另一列最大的行
- arrays - Bash Array:将元素解释为文字
- java - GCP PubSub:创建配置类以发布消息