将计算列添加到 Pandas 数据透视表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26313881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:34:03  来源:igfitidea点击:

Add calculated column to a pandas pivot table

pythonpandas

提问by Pynewbie

I have created a pandas data frame and then converted it into pivot table.

我创建了一个Pandas数据框,然后将其转换为数据透视表。

My pivot table looks like this:

我的数据透视表如下所示:

Operators   TotalCB     Qd(cb)  Autopass(cb)
Aircel India    55        11       44
Airtel Ghana    20        17        3
Airtel India    41         9        9
Airtel Kenya    9          4        5
Airtel Nigeria  24        17        7
AT&T USA        18        10        8

I was wondering how to add calculated columns so that I get my pivot table with Autopass% (Autopass(cb)/TotalCB*100) just like we are able to create them in Excel using calculated field option.

我想知道如何添加计算列,以便使用 Autopass% ( Autopass(cb)/TotalCB*100)获取数据透视表,就像我们能够使用计算字段选项在 Excel 中创建它们一样。

I want my pivot table output to be something like below:

我希望我的数据透视表输出如下所示:

Operators   TotalCB     Qd(cb)  Autopass(cb)    Qd(cb)% Autopass(cb)%
Aircel India    55          11    44             20%     80%
Airtel Ghana    20          17     3             85%     15%
Airtel India    41          29     9             71%     22%
Airtel Kenya     9           4     5             44%     56%
AT&T USA        18          10     8             56%     44%

How do I define the function which calculates the percentage columns and how to apply that function to my two columns namely Qd(cb)and Autopass(cb)to give me additional calculated columns

我如何定义计算百分比列的函数以及如何将该函数应用于我的两列Qd(cb)Autopass(cb)为我提供额外的计算列

采纳答案by Korem

This should do it, assuming datais your pivoted dataframe:

这应该可以做到,假设data是您的旋转数据框:

data['Autopass(cb)%'] = data['Autopass(cb)'] / data['TotalCB'] * 100
data['Qd(cb)%'] = data['Qd(cb)'] / data['TotalCB'] * 100

Adding a new column to a dataframe is as simple as df['colname'] = new_series. Here we assign it with your requested function, when we do it as a vector operation it creates a new series.

向数据框中添加新列就像df['colname'] = new_series. 在这里,我们将您请求的功能分配给它,当我们将其作为向量操作进行时,它会创建一个新系列。