Python 从数据帧中选择第n个最低值(每行!)

Python 从数据帧中选择第n个最低值(每行!),python,pandas,dataframe,Python,Pandas,Dataframe,我正在寻找一种从数据帧中选择值(按行)的解决方案。 以下是我已经拥有的: np.random.seed(1) df = pd.DataFrame(np.random.randint(1,10, (10, 10))) df.columns = list('ABCDEFGHIJ') N = 2 idx = np.argsort(df.values, 1)[:, 0:N] df= pd.concat([pd.DataFrame(df.values.take(idx), index=df.index

我正在寻找一种从数据帧中选择值(按行)的解决方案。 以下是我已经拥有的:

np.random.seed(1)
df = pd.DataFrame(np.random.randint(1,10, (10, 10)))
df.columns = list('ABCDEFGHIJ')

N = 2
idx = np.argsort(df.values, 1)[:, 0:N]

df= pd.concat([pd.DataFrame(df.values.take(idx), index=df.index), pd.DataFrame(df.columns[idx], index=df.index)],keys=['Value', 'Columns']).sort_index(level=1)
现在我有了每个值的索引/位置,但是如果我试图从数据帧获取值,它只获取第一行的值。 我必须在代码中更改什么

df看起来像:

   A  B  C  D  E  F  G  H  I  J
0  6  9  6  1  1  2  8  7  3  5
1  6  3  5  3  5  8  8  2  8  1
2  7  8  7  2  1  2  9  9  4  9
....
我的输出应该如下所示:

0  D E
0  1 1
1  J H
1  1 2
您可以使用从dataframe获取值。用于筛选获取的值和相应的列名

# idx is the same as the one used in the question.

vals = np.take_along_axis(df.values, idx, axis=1)
cols = df.columns.values[idx]
indices = np.r_[: len(vals)] # same as np.arange(len(vals))

out = np.insert(vals.astype(str), indices , cols, axis=0)
index = np.repeat(indices, 2)
df = pd.DataFrame(out, index=index)

   0  1
0  D  E
0  1  1
1  J  H
1  1  2
2  E  D
2  1  2
3  E  I
3  2  2
4  A  D
4  1  1
5  I  J
5  1  3
6  E  I
6  1  2
7  B  H
7  1  3
8  G  I
8  1  1
9  E  A
9  1  2

预期输出是什么?预期输出应该为每一行提供第n个最低值。您可以将预期输出发布到问题中吗?你可以从这里直接排序吗
np.sort(df.to_numpy(),axis=1)[:,:N]
@HenryYik直接排序,然后我们就可以根据每行中的N个最小值确定要取哪个列名。谢谢,它工作得非常好!但是如何从原始df中获取索引呢?因此,如果df的索引是不同的值,而不是0到x@Wayne2非常感谢。也是个好问题。如果它解决了你的问题,请考虑通过点击答案旁边的嘀嗒声来接受这个答案。通道2