Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获得一行中第二高的值?_Python_Pandas - Fatal编程技术网

Python 如何获得一行中第二高的值?

Python 如何获得一行中第二高的值?,python,pandas,Python,Pandas,我想从数据帧中为每一行获取某个部分的第二高值。我该怎么做 我尝试了以下代码,但不起作用: df.iloc[:, 5:-3].nlargest(2)(axis=1, level=2) 是否有其他方法获得此信息?我认为您需要按行排序,然后选择: a = np.sort(df.iloc[:, 5:-3], axis=1)[:, -2] 样本: np.random.seed(100) df = pd.DataFrame(np.random.randint(10, size=(10,10))) pri

我想从数据帧中为每一行获取某个部分的第二高值。我该怎么做

我尝试了以下代码,但不起作用:

df.iloc[:, 5:-3].nlargest(2)(axis=1, level=2)

是否有其他方法获得此信息?

我认为您需要按行排序,然后选择:

a = np.sort(df.iloc[:, 5:-3], axis=1)[:, -2]
样本

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(10,10)))
print (df)
   0  1  2  3  4  5  6  7  8  9
0  8  8  3  7  7  0  4  2  5  2
1  2  2  1  0  8  4  0  9  6  2
2  4  1  5  3  4  4  3  7  1  1
3  7  7  0  2  9  9  3  2  5  8
4  1  0  7  6  2  0  8  2  5  1
5  8  1  5  4  2  8  3  5  0  9
6  3  6  3  4  7  6  3  9  0  4
7  4  5  7  6  6  2  4  2  7  1
8  6  6  0  7  2  3  5  4  2  4
9  3  7  9  0  0  5  9  6  6  5

print (df.iloc[:, 5:-3])
   5  6
0  0  4
1  4  0
2  4  3
3  9  3
4  0  8
5  8  3
6  6  3
7  2  4
8  3  5
9  5  9

a = np.sort(df.iloc[:, 5:-3], axis=1)[:, -2]
print (a)
[0 0 3 3 0 3 3 2 3 5]
如果需要两个值:

a = df.iloc[:, 5:-3].values
b = pd.DataFrame(a[np.arange(len(a))[:, None], np.argsort(a, axis=1)])
print (b)
   0  1
0  0  4
1  0  4
2  3  4
3  3  9
4  0  8
5  3  8
6  3  6
7  2  4
8  3  5
9  5  9

您需要使用
numpy.sort()
对数据帧进行排序,然后获取第二个值

import numpy as np
second = np.sort(df.iloc[:, 5:-3], axis=1)[:, 1]

使用“轴为1时应用”,可以找到每行的第二大值。找到前两个最大的,然后得到最后一个

df.iloc[:, 5:-3].apply(lambda row: row.nlargest(2).values[-1],axis=1)
范例

下面的代码在每行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

你测试过吗?是的,我测试过。这将输出行中的第二个最低值。因为如果使用
[:,1]
它将为我返回第一个最大值。
[:,1]
将返回第二个最低值。嘿!这是一个很好的解决方案。这不是输出第二高的值。我的行中几乎没有空值,这会输出空值。您可以添加数据样本并使用空值预期输出吗?
a=np.sort(df.iloc[:,5:-3],axis=1)[:,-2]
是正确答案。使用
[:,0]
进行索引只是偶然的,因为您使用的是10x2切片。如果您创建一个更大的数据集(比如16x16),它将变得显而易见。