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

How to put the max of 3 separate columns in a new column in python/pandas

for example we have:

a b c
1 1 3
2 4 1
3 2 1

And now using python I’m trying to create this:

a b c max
1 1 3 3c
2 4 1 4b
3 2 1 3a

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

>Solution :

If need match first maximal column join max converted to strings with DataFrame.idxmax for columns names by max:

cols = ['a','b','c']
df['max'] = df[cols].max(axis=1).astype(str).str.cat(df[cols].idxmax(axis=1))
print (df)
   a  b  c max
0  1  1  3  3c
1  2  4  1  4b
2  3  2  1  3a

If possible multiple max values and need all matched columns use DataFrame.dot trick with separator ,:

print (df)
   a  b  c
0  3  1  3
1  2  4  1
2  3  2  1

cols = ['a','b','c']

max1 = df[cols].max(axis=1)
s = df[cols].eq(max1, axis=0).dot(pd.Index(cols) + ',').str[:-1]
df['max'] = max1.astype(str).str.cat(s)
    
print (df)
   a  b  c   max
0  3  1  3  3a,c
1  2  4  1    4b
2  3  2  1    3a
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