Add calculated column to pandas pivot table

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

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 to get our pivot table using Autopass% ( Autopass(cb)/TotalCB*100 ) in the same way as we can create them in Excel using the calculated field.

I want my pivot table result to look something like this:

 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 to define a function that calculates percentage columns and how to apply this function to my two columns, namely Qd(cb) and Autopass(cb) , to give me additional calculated columns

+6
source share
1 answer

This should do it, assuming data is your rotary file frame:

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

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

+2
source

Source: https://habr.com/ru/post/976605/


All Articles