Reputation: 1248
Suppose i have this dataframe
A B C
0 1 2 3
1 4 5 6
2 7 8 9
SUM 12 15 18
now i want to divide each element by their respective column "SUM"
. Example (1/12),(8/15) etc, and fill it up in place of the numbers.
I can loop it, but that would be time consuming and moreover i am sure there must be some way in which pandas
can do it without looping.
something like this is done Pandas sum across columns and divide each cell from that value here, but its for row totals. I want to know how to do it for column totals.
Upvotes: 2
Views: 3819
Reputation: 394021
If you select the last row using iloc
then you can pass this to div
:
In [20]:
df.div(df.iloc[-1])
Out[20]:
A B C
0 0.083333 0.133333 0.166667
1 0.333333 0.333333 0.333333
2 0.583333 0.533333 0.500000
SUM 1.000000 1.000000 1.000000
Upvotes: 4