Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Select a complex subset of columns from a np.array

I want have an array X, and I want to select, for example, the 1st, 5th, 7th, and all of the last 1000 columns (non-overlapping). I know I can get the 1st, 5th, 7th columns using X[:, [0,4,6]] and the last 1000 columns by X[:, -1000:]. But is there a quick and easy way to select them all together using one line/object?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use np.r_:

X[:, np.r_[[0,4,6],-1000:0]]

Example with a (5, 20) array selecting 0,4,6 and the last 10:

X = np.arange(100).reshape(-1, 20)
X[:, np.r_[[0,4,6],-10:0]]

# array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
#        [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
#        [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
#        [60, 61, 62, 63, 64, 65, 66, 67, 68, 69]])

Intermediate:

np.r_[[0,4,6],-10:0]
# array([  0,   4,   6, -10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1])

Note that you should ensure that the slices are not overlapping, else you would have duplicated columns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading