Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding indices that would sort numpy column returns zeros

Tags:

python

numpy

I am trying to get the indices that would sort each column of an array using the function argsort. However, it keeps simply returning zeros instead of the true indices. For example:

x = np.matrix([[5, 2, 6], [3, 4, 1]])
print(x)

print(x[:,0])
print(x[:,1])
print(x[:,2])

print(x[:,0].argsort())
print(x[:,1].argsort())
print(x[:,2].argsort())

I am expecting this to return three arrays. [1 0], [0 1] and [1 0] denoting the indices of each column if it were sorted, however, instead I get three arrays that all contain zeros.

Any help much appreciated!

like image 942
Ollie Avatar asked Oct 29 '25 19:10

Ollie


1 Answers

Indexing a matrix with a slice always returns another 2-d matrix. (This behavior is not the same as for a regular numpy array.) See, for example, the output of x[:,0]:

In [133]: x[:,0]
Out[133]: 
matrix([[5],
        [3]])

x[:,0] is a matrix with shape (2, 1). To argsort the first (and only) column of that matrix, you have to tell argsort to use the first axis:

In [135]: x[:,0].argsort(axis=0)
Out[135]: 
matrix([[1],
        [0]])

The default (axis=-1) is to use the last axis, and since the rows in that matrix have length 1, the result when axis is not given is a column of zeros.


By the way, you can do all the columns at once:

In [138]: x
Out[138]: 
matrix([[5, 2, 6],
        [3, 4, 1]])

In [139]: x.argsort(axis=0)
Out[139]: 
matrix([[1, 0, 1],
        [0, 1, 0]])
like image 93
Warren Weckesser Avatar answered Oct 31 '25 08:10

Warren Weckesser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!