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

Getting a maximum value from a list in pandas columns

I have the following dataframe.

df

Col1                     Col2           Col3
0.00               [50.00, 100.00]      Tall
50.00                     0.00           NaN
[0.00, 50.00, 60.00]      10.00         Short  

I would like to apply max-of-all in the list values and would like to get the following result.

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

Col1        Col2       Col3
0.00       100.00      Tall
50.00       0.00       NaN
60.00      10.00      Short

I have tried this but couldn’t succeed.

df = df.apply(lambda x: max(map(int, x.split(','))))

Can any one help on this?

>Solution :

Method1:

You can use applymap here which will check if the instance is a list, return max of list else return element as is:

out = df.applymap(lambda x: max(x) if isinstance(x,list) else x)

Method 2:

You can stack the dataframe and then apply the function on series and then unstack to get original shape:

out = df.stack().apply(lambda x: max(x) if isinstance(x,list) else x).unstack()

print(out)

   Col1   Col2   Col3
0   0.0  100.0   Tall
1  50.0    0.0    NaN
2  60.0   10.0  Short

Note that this assumes that the rows with list are actual python lists and not a string representation of a list.

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