简体   繁体   English

从 pandas 列中的列表中获取最大值

[英]Getting a maximum value from a list in pandas columns

I have the following dataframe.我有以下 dataframe。

df 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.我想在列表值中应用 max-of-all 并希望得到以下结果。

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?有人可以帮忙吗?

Method1:方法1:

You can use applymap here which will check if the instance is a list, return max of list else return element as is:您可以在此处使用 applymap 来检查实例是否为列表,返回列表的最大值,否则按原样返回元素:

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:您可以堆叠 dataframe 然后将 function 应用到系列上,然后取消堆叠以获得原始形状:

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.请注意,这假定带有列表的行是实际的 python 列表,而不是列表的字符串表示形式。

You can also use this:你也可以使用这个:

df = df[df.columns].apply(lambda x: x.explode().groupby(level=0).max())

OUTPUT

   Col1  Col2   Col3
0   0.0   100   Tall
1  50.0     0    NaN
2  60.0    10  Short

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM