【发布时间】:2021-01-31 01:29:25
【问题描述】:
我需要完成几件事:
-
按国家和产品分组列
-
执行聚合得到:
- percentage of my Products column for each country - Calculate the sum of columns Volume and Profit and UnrealizedProfit (2 columns 1st=Volume, 2nd= Profit + UnrealizedProfit) -
同时显示其他列
我的数据框:
Country Sector Products Volume Profit UnrealizedProfit
0 Country_1 Sector1 Product_1 50 5 4
1 Country_1 Sector2 Product_2 100 6 3
2 Country_2 Sector1 Product_1 150 3 -1
3 Country_2 Sector2 Product_2 200 -1 5
4 Country_1 Sector1 Product_2 100 7 10
5 Country_2 Sector2 Product_2 200 -3 -1
6 Country_2 Sector1 Product_1 150 2 -1
7 Country_1 Sector2 Product_1 50 5 -3
注意:我的实际数据框中有几千行。
所需的输出如下所示:
Country Sector Products Product% Volume ExpectedProfit
0 Country_1 Sector1 Product_1 0.138 100 11
1 Country_1 Sector2 Product_2 0.861 200 26
2 Country_2 Sector1 Product_1 0.667 300 3
3 Country_2 Sector2 Product_2 0.333 400 0
我一次只能进行一次聚合,但不是两次。 到目前为止:
df = (data1.groupby('Country')['Products']
.value_counts(normalize=True,sort=False)
.reset_index(name='Product%'))
print (df)
这段代码给了我:
Country Products Product%
0 Country 1 Product 1 0.138
1 Country 1 Product 2 0.861
2 Country 2 Product 1 0.667
3 Country 2 Product 2 0.333
产品的每个频率都是基于相关国家 --> sum(Country1) =100%, sum(Country2)=100%...
对于我设法复制的卷:
df = (data1.groupby(['Country','Product'])['Volume']
.sum()
.reset_index(name='Volume'))
我在 groupby() 中添加了产品,因为我想查看每个产品和国家/地区的数量。
目标是结合 Products% 和 Volume 并添加 ExpectedProfit 如前所述,我不知道如何将其结合起来并为利润进行聚合(利润+未实现利润) 以及显示部门(我猜部门可以包含在 Groupby() 中,因为每个部门都有几个产品。
感谢您的帮助!
【问题讨论】:
-
请分享您的数据框样本以进行处理。
-
我添加了一个示例
标签: python pandas group-by aggregate-functions