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:
JavaScript
x
5
1
pd.DataFrame(
2
{'A': {0: 1, 1: 1},
3
'B': {0: 1, 1: 2},
4
'C': {0: 1, 1: 9},})
5
Output:
JavaScript
1
5
1
pd.DataFrame(
2
{'A': {0: 0.5, 1: 0.5},
3
'B': {0: 0.333, 1: 0.666},
4
'C': {0: 1, 0.1: 0.9},})
5
Advertisement
Answer
How about apply
?
JavaScript
1
13
13
1
import pandas as pd
2
3
df = pd.DataFrame(
4
{'A': {0: 1, 1: 1},
5
'B': {0: 1, 1: 2},
6
'C': {0: 1, 1: 9},})
7
8
df = df.apply(lambda col: col / sum(col))
9
print(df)
10
# A B C
11
# 0 0.5 0.333333 0.1
12
# 1 0.5 0.666667 0.9
13