我已经使用pandas数据框架将一个excel表格转换成一个数据透视表。我想做一些计算。创建的透视表如下所示。第一行是标题。我想计算每一项的收益率,例如,Badam = T/HA (即,Badam = 14558/4811的收益率),并添加收益率作为我的最后一列。T和HA来自"Unit“列。我也找不到任何可以继续下去的例子。如果有专家的帮助那就太好了。

或者,对于这种计算,我应该从数据透视表转移到"groupby“吗?谢谢。
发布于 2019-10-18 17:33:44
示例数据:
state District Year Item Unit Amount
0 TN Trichy 2016 Badam HA 4811
1 TN Trichy 2016 Badam N 59
2 TN Trichy 2016 Badam T 14558
3 TN Trichy 2016 Carrots HA 18973
4 TN Trichy 2016 Carrots N 123
5 TN Trichy 2016 Carrots T 35990代码如下:
res = df.pivot_table(index=['state','District','Year','Item'], values = 'Amount', columns =['Unit'])
Out[25]:
Unit HA N T
state District Year Item
TN Trichy 2016 Badam 4811 59 14558
Carrots 18973 123 35990
res.assign(result = res['T']/res['HA'])
Out[28]:
Unit HA N T result
state District Year Item
TN Trichy 2016 Badam 4811 59 14558 3.025982
Carrots 18973 123 35990 1.896906发布于 2019-10-21 16:22:59
谢谢。正如Alexey提到的那样,我尝试并计算了结果。我试着用(to_excel)把数据透视表转换成excel表格。但只有最后4列被写入excel表格(即) "HA,N,T和结果“,而不是州,地区,年份和项目。如何将8列全部写入excel表格?
接下来我尝试了res.stack()。这是pandas系列,然后将它们转换成数据帧,然后写入excel工作表。这也是将所有列写入到excel文件中的单个高列中。这是否意味着当我尝试使用res.assign(result = res['T']/res['HA'])进行计算时,数据透视表会丢失?有没有人能解释一下如何取消透视这个表
state District Year Item HA N T results
TN Trichy 2016 Badam 4811 59 14558 3.025982
TN Trichy 2016 Carrots 18973 123 35990 1.896906谢谢。
https://stackoverflow.com/questions/58447488
复制相似问题