Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pd.DataFrame(
{'A': {0: 0.5, 1: 0.5},
 'B': {0: 0.333, 1: 0.666},
 'C': {0: 1, 0.1: 0.9},})

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading