M PAUL - 9 months ago 128

Python Question

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"`

I can loop it, but that would be time consuming and moreover i am sure there must be some way in which

`pandas`

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.

Answer

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
```