我想从数据帧中获取每一行的某个部分的第二高值。我该怎么做呢?
我已经尝试过以下代码,但它不起作用:
df.iloc[:, 5:-3].nlargest(2)(axis=1, level=2)
还有其他方法可以获得这个吗?
使用 apply 和 axis=1 ,您可以找到每行的第二大值。找到前两个最大的,然后得到最后一个
df.iloc[:, 5:-3].apply(lambda row: row.nlargest(2).values[-1],axis=1)
Example
下面的代码查找 df 的每一行中的第二大值。
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df = pd.DataFrame({'Col{}'.format(i):np.random.randint(0,100,5) for i in range(5)})
In [4]: df
Out[4]:
Col0 Col1 Col2 Col3 Col4
0 82 32 14 62 90
1 62 32 74 62 72
2 31 79 22 17 3
3 42 54 66 93 50
4 13 88 6 46 69
In [5]: df.apply(lambda row: row.nlargest(2).values[-1],axis=1)
Out[5]:
0 82
1 72
2 31
3 66
4 69
dtype: int64
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)