Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.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
Pandas 按行返回前3个绝对值的原始值?_Pandas_Numpy - Fatal编程技术网

Pandas 按行返回前3个绝对值的原始值?

Pandas 按行返回前3个绝对值的原始值?,pandas,numpy,Pandas,Numpy,在按绝对值排序后,我想返回前3个值。那么像这样的df 0 1 2 3 0 2.822437 1.667583 -1.505558 -0.608644 1 0.357442 1.159013 -1.634652 2.270087 2 1.988308 1.129140 -0.725482 0.049260 你应该还这个 0 First Second Third 0 2.82243z 1.66758

在按绝对值排序后,我想返回前3个值。那么像这样的df

    0   1   2   3
0   2.822437    1.667583    -1.505558   -0.608644
1   0.357442    1.159013    -1.634652   2.270087
2   1.988308    1.129140    -0.725482   0.049260
你应该还这个

0   First   Second  Third
0   2.82243z    1.667583    -1.505558
1   1.159013    -1.634652   2.270087
2   1.988308    1.129140    -0.725482
如何才能最好地实现这一点?我需要根据绝对值对它们进行排序,但我需要返回原始值

谢谢这里有一个方法

out = pd.DataFrame(df.apply(lambda x : sorted(x,key=abs)[1:][::-1],1).tolist())
Out[16]: 
          0         1         2
0  2.822437  1.667583 -1.505558
1  2.270087 -1.634652  1.159013
2  1.988308  1.129140 -0.725482
这里有一条路

out = pd.DataFrame(df.apply(lambda x : sorted(x,key=abs)[1:][::-1],1).tolist())
Out[16]: 
          0         1         2
0  2.822437  1.667583 -1.505558
1  2.270087 -1.634652  1.159013
2  1.988308  1.129140 -0.725482

不确定这是否是你想要的;这将使用numpy在重建数据帧之前完成大部分工作:

array = df.to_numpy()
# gets the absolute value
# then gets the indices that would sort the array
# since just the top three is needed and the max
# we drop the first column and flip the rows
positions = np.argsort(np.abs(array), axis=1)[::-1, 1:]
new_array = np.take_along_axis(array, positions, axis=1)[:, ::-1]
new_array = pd.DataFrame(new_array, columns=["First", "Second", "Third"])
new_array

    First         Second    Third
0   2.822437    1.667583    -1.505558
1   2.270087    -1.634652   1.159013
2   1.988308    1.129140    -0.725482

不确定这是否是你想要的;这将使用numpy在重建数据帧之前完成大部分工作:

array = df.to_numpy()
# gets the absolute value
# then gets the indices that would sort the array
# since just the top three is needed and the max
# we drop the first column and flip the rows
positions = np.argsort(np.abs(array), axis=1)[::-1, 1:]
new_array = np.take_along_axis(array, positions, axis=1)[:, ::-1]
new_array = pd.DataFrame(new_array, columns=["First", "Second", "Third"])
new_array

    First         Second    Third
0   2.822437    1.667583    -1.505558
1   2.270087    -1.634652   1.159013
2   1.988308    1.129140    -0.725482