python - 计算 Pandas 子组的百分比

标签 python pandas

我有一个df

df = pd.DataFrame({'group':['A','A','A','A','A',
                            'B','B','B','B','B',
                            'C','C','C','C','C'],
                  'category': ['zero','first', 'second', 'first+second', 'total',
                               'zero', 'first', 'second', 'first+second', 'total',
                               'zero','first', 'second', 'first+second', 'total'],
                  'sales': [50,100,75,175,225, 
                            5,10,15,25,30,
                            1000,2000,3000,3000,4000]})

我正在尝试计算组内每个类别的 %,问题是 category first+second total 是之前类别的总和,不应计入计算。

我试过:

df['%'] = (df['sales'] / df.groupby(['group'])['sales'].transform('sum')) * 100

但现在 total 只有 36% 而它应该是 100% 然后整个百分比是错误的。 如果我像这样隔离组:

my_df['%_v2'] =(my_df['sales'] / my_df[my_df.category.isin(['zero', 'first', 'second'])].groupby(['group'])['sales'].transform('sum')) * 100

然后 zero, first, second % 是正确的,但是我在 first+second 中得到了 nan 并且总计:

enter image description here

而不是 nan 我想得到 (175/225) * 100 的百分比 first+second 225/225 表示总计

最佳答案

想法是在 Series.where 中用 NaN 替换不匹配的值:

s = (df['sales'].where(df.category.isin(['zero', 'first', 'second']))
                .groupby(df['group'])
                .transform('sum'))

df['%'] = df['sales'].div(s).mul(100)
print (df)
   group      category  sales           %
0      A          zero     50   22.222222
1      A         first    100   44.444444
2      A        second     75   33.333333
3      A  first+second    175   77.777778
4      A         total    225  100.000000
5      B          zero      5   16.666667
6      B         first     10   33.333333
7      B        second     15   50.000000
8      B  first+second     25   83.333333
9      B         total     30  100.000000
10     C          zero   1000   16.666667
11     C         first   2000   33.333333
12     C        second   3000   50.000000
13     C  first+second   3000   50.000000
14     C         total   4000  100.000000

关于python - 计算 Pandas 子组的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69657496/

相关文章:

javascript - 如何使用 flask 将二维 float 组从 javascript 发送到 python

python - 在 pandas 列上应用函数

python - 根据每个列类型获取数据框的均值和模式

python - Pandas numpy复杂如果

python - Networkx:如何绘制彩色边缘?

python - 用于计算间隔的工具/库,如 "last thursday of the month"

python - 无法在我的 Django 应用程序的 models.py 中使用 imageField 显示照片?

python - 如何循环读取巨型CSV文件

python - Pandas 保存时添加一个空列

python - Holoviews 更改数据着色器颜色图