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

Pandas: sum DataFrame column for max value only

I have the following DataFrame:

df = pd.DataFrame({'a': [0.28,0,0.25, 0.85, 0.1], 'b': [0.5,0.5,0, 0.75, 0.1], 'c':[0.33,0.7,0.25, 0.2, 0.5],
                   'd':[0,0.25,0.2, 0.66, 0.1]})
df

enter image description here

I would like to add a row ‘count’ at the end of the dataframe which is the sum of the max value of each row, but sum with its column. for example column b, it has only a max value in the first row, so the count of this column, in the end, is only 0.5, etc.

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

the results should look like this:

enter image description here

red cell represents a max value in this row

>Solution :

where

df.append(
    df.where(  # only look at values that are max for the row
        df.eq(  # compare max values to all values in row just in case there are more than 1
            df.max(axis=1),  # actually get max values
            axis=0
        )
    ).sum().rename('count')
)

          a     b     c     d
0      0.28  0.50  0.33  0.00
1      0.00  0.60  0.50  0.25
2      0.25  0.00  1.00  0.20
3      0.85  0.75  0.20  0.66
4      0.10  0.10  0.50  0.10
count  0.85  1.10  1.50  0.00
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