'In Pandas sum columns and change values to proportion of sum
If I have the following DataFrame, how can I convert the value in each row to the proportion of the total of the columns?
Input:
pd.DataFrame(
{'A': {0: 1, 1: 1},
'B': {0: 1, 1: 2},
'C': {0: 1, 1: 9},})
Output:
pd.DataFrame(
{'A': {0: 0.5, 1: 0.5},
'B': {0: 0.333, 1: 0.666},
'C': {0: 1, 0.1: 0.9},})
Solution 1:[1]
How about apply
?
import pandas as pd
df = pd.DataFrame(
{'A': {0: 1, 1: 1},
'B': {0: 1, 1: 2},
'C': {0: 1, 1: 9},})
df = df.apply(lambda col: col / sum(col))
print(df)
# A B C
# 0 0.5 0.333333 0.1
# 1 0.5 0.666667 0.9
Solution 2:[2]
Try
out = df.div(df.sum())
Out[549]:
A B C
0 0.5 0.333333 0.1
1 0.5 0.666667 0.9
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | j1-lee |
Solution 2 | BENY |