按多列分组的熊猫df百分比计数

问题描述

我有两只熊猫df。数据按月,类别,产品分组。它还有一个“支出”列。我需要计算支出百分比列。以下是df_raw的示例:

                                         spend_sum
category     month     product_list
Home          1         A                    10
                        B                    20
                        C                    30

Home          2         A                    40
                        B                    50
                        C                    60

下面是df_new的示例:

                                         spend_sum
category     month     product_list
Home          1         A                    1
                        B                    2
                        C                    3

Home          2         A                    20
                        B                    10
                        C                    5

我的代码是:

df_raw = df.explode('product_list').groupby(['category','month','product_list']).count()

我需要除df_new['spend_sum'] / df_raw['spend_sum'] 所需的输出是:

                                         percentage
category     month     product_list
Home          1         A                    0.1
                        B                    0.1
                        C                    0.1

Home          2         A                    0.5
                        B                    0.2
                        C                    0.008

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)