Reputation: 715
I have a very basic table:
gov dis value1 value2
0 a a_1 8 8
1 a a_2 7 18
2 a a_3 3 2
3 a a_4 12 12
4 b b_1 4 11
5 b b_2 16 9.....
I can create a basic pivot table from this using:
t = pd.pivot_table(per_t,index=["gov"],values=['value1'],aggfunc=[np.mean])
To create:
mean
value1
gov
a 7.5
b 12.0
I want to convert this into percentages of the column, and have been unable to find anything clear on how to do this? Is there a way of altering the aggfunc to calculate the column percentage?
Upvotes: 2
Views: 1512
Reputation: 375565
You can divide by the sum:
In [11]: t.sum()
Out[11]:
mean value1 17.5
dtype: float64
In [12]: t / t.sum()
Out[12]:
mean
value1
gov
a 0.428571
b 0.571429
In [13]: (t / t.sum()) * 100
Out[13]:
mean
value1
gov
a 42.857143
b 57.142857
Note: I think you have to do this after the pivot as an aggregation function doesn't have access to the other groups.
Upvotes: 3