首页 > 解决方案 > 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 列。我想为其他专栏做类似的事情。

标签: pythonpandas

解决方案


使用aggwith add_prefixthen mergeit 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

推荐阅读