Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

finding indices that would sort numpy column returns zeros

Writer Emily Wong

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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