添加新列和查找组总数百分比的常见 Pandas 方法

Common Pandas approaches to adding a new column and finding percentage of group total

逐渐将我的任务从 excel 转移到 pandas,在创建依赖于分组和其他两个列的值的新列时,有哪些常用方法?

在 excel 中,这可以通过 =B2/SUMIFS(B:B,A:A,A2) 来完成——在 pandas 中是否有类似的简单方法?我试过 .transform 但没有成功。

示例如下:

import pandas as pd

data = [{'GROUP': 1, 'VALUE': 3},
        {'GROUP': 1, 'VALUE': 3},
        {'GROUP': 1, 'VALUE': 4},
        {'GROUP': 2, 'VALUE': 2},
        {'GROUP': 2, 'VALUE': 2},
        {'GROUP': 2, 'VALUE': 6}]

df = pd.DataFrame(data)

df['PERC_TOTAL'] = df['VALUE'] / df['VALUE'].sum() 

#df['GRP_PERC_TOTAL'] = ??? idx 0 and 1 would equal 0.30 idx 2 would equal .40
df

gropuby-transform策略应该走在正确的轨道上:

df['GRP_PERC_TOTAL'] = df["VALUE"] / df.groupby("GROUP")["VALUE"].transform("sum")

结果

print(df)
   GROUP  VALUE  PERC_TOTAL  GRP_PERC_TOTAL
0      1      3        0.15             0.3
1      1      3        0.15             0.3
2      1      4        0.20             0.4
3      2      2        0.10             0.2
4      2      2        0.10             0.2
5      2      6        0.30             0.6