Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting matrix columns based on list values with Python

I have an N x 100 numpy matrix containing any kind of numbers that I want to sort.

In order for it to be more visual, I will now fill it out with dummy values:

import numpy as np

X = np.array( [[float(number) for number in range(100)] for _ in range(10)] )

# X 
[[   0.    1.    2. ...,   97.   98.  99.]
 [   0.    1.    2. ...,   97.   98.  99.]
 [   0.    1.    2. ...,   97.   98.  99.]
 ..., 
 [   0.    1.    2. ...,   97.   98.  99.]
 [   0.    1.    2. ...,   97.   98.  99.]
 [   0.    1.    2. ...,   97.   98.  99.]]

I want to sort the columns for all N rows using the following 100-element list as the key:

# s
["butterfly", "zebra", "cactus", ... "animal", "xylitol", "yoyo"]

So that the output looks like this:

# X_sorted
[[   97.    0.    2. ...,   98.   99.  1.]
 [   97.    0.    2. ...,   98.   99.  1.]
 [   97.    0.    2. ...,   98.   99.  1.]
 ..., 
 [   97.    0.    2. ...,   98.   99.  1.]
 [   97.    0.    2. ...,   98.   99.  1.]
 [   97.    0.    2. ...,   98.   99.  1.]]

So basically, I want to retrieve the alphabetical sorting output of s, and apply it to the columns of X.

How can I achieve this?

I am familiar with the sort command using key, but I do not know how to apply this to the matrix columns in this scenario.


1 Answers

If your objects were numpy arrays (as in X = np.array(X); s = np.array(s), then you could use np.argsort, which returns an array of the indices that would make the input sorted.

X_sorted = X[:, np.argsort(s)]
like image 169
Mad Physicist Avatar answered Jul 18 '26 21:07

Mad Physicist



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!