当前位置:网站首页>How to arrange the dataframe from small to large according to the absolute value of a column?

How to arrange the dataframe from small to large according to the absolute value of a column?

2022-06-11 06:21:00 Geek student

For example, according to ‘a’ The absolute values of the columns are sorted from small to large

df.iloc[df['a'].abs().argsort()]

In absolute order from big to small

df.iloc[df['a'].abs().argsort()[::-1]]

First step : So let's define one array data
import numpy as np
x=np.array([2,4,5,3,-10,1])

The second step : Output results :
y=np.argsort(x)
print(y)
The output is :y=[4 5 0 3 1 2]

The third step : summary :
argsort() The function is to x The elements in are arranged from small to large , Extract the corresponding index( Reference no. )
for example :x[4]=-10 Minimum , therefore y[0]=4,
Empathy :x[2]=5 Maximum , therefore y[5]=2.

See the following official cases :

One dimensional array: One dimensional array 
    >>> x = np.array([3, 1, 2])
    >>> np.argsort(x)
    array([1, 2, 0])

    Two-dimensional array: Two dimensional array 

    >>> x = np.array([[0, 3], [2, 2]])
    >>> x
    array([[0, 3],
           [2, 2]])

    >>> np.argsort(x, axis=0) # Sort by column 
    array([[0, 1],
           [1, 0]])

    >>> np.argsort(x, axis=1) # Sort by row 
    array([[0, 1],
           [0, 1]])
	
	>>> x = np.array([3, 1, 2])
	>>> np.argsort(x) # In ascending order 
	array([1, 2, 0])
	>>> np.argsort(-x) # Sort in descending order 
	array([0, 2, 1])
原网站

版权声明
本文为[Geek student]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020527521448.html