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},})
Advertisement
Answer
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