Finding Indices That Would Sort Numpy Column Returns Zeros

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!

1 Answer

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]])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest