我有一组数据,我已经从excel xlsx文件导入。之后,我决定找出每个客户群的总利润百分比。我设法使用pivot_table来总结每个客户群的总利润。但是,我也想知道百分比。我怎么做?
pivot_table
profit = df.pivot_table(index = ['Customer Segment'], values = ['Profit'], aggfunc=sum)
结果到目前为止
Customer Segment Profit
A a
B b
C c
D d
也许将百分比列添加到数据透视表是一种理想的方法。但是我该怎么做呢?
怎么样
df['percent'] = df['Profit']/sum(df['Profit'])
例如,您有此数据框:
Customer Segment Customer Profit
0 A AAA 12
1 B BBB 43
2 C CCC 45
3 D DDD 23
4 D EEE 67
5 C FFF 21
6 B GGG 45
7 A JJJ 67
8 A KKK 32
9 B LLL 13
10 C MMM 43
11 D NNN 13
从上面的数据框中,您想要制作数据透视表。
import pandas as pd
import numpy as np
tableframe = pd.pivot_table(df, values='Profit', index=['Customer Segment'], aggfunc=np.sum)
这是您的数据透视表:
Profit
Customer Segment
A 111
B 101
C 109
D 103
现在,您要向表框添加另一列,然后计算百分比。
tableframe['percentage'] = ((tableframe.Profit / tableframe.Profit.sum()) * 100)
这是您的最终表格框架:
Profit percentage
Customer Segment
A 111 26.179245
B 101 23.820755
C 109 25.707547
D 103 24.292453