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

get columns from numpy array in specific format given column indices

I have a numpy array like this:

import numpy as np

# Create a NumPy array
array_data = np.array([[1, 2, 3],
                       [4, 5, 6],
                       [7, 8, 9]])

and yes I can get the 2nd column like this:

column_index = 1
selected_column = array_data[:,1]
print(selected_column)

giving:

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

[2 5 8]

I need it like this though:

[[2]
 [5]
 [8]]

which I can get using:

selected_column = array_data[:, column_index:column_index+1]
print(selected_column)

Now you wonder, why ask this question. Well I would like to actually provide several column indices (coming from a pandas data frame with provided column names) whilst still getting the array like the last output.

selected_column = array_data[:, column_index:column_index+1]

>Solution :

You could use reshape?

array_data[:, column_index].reshape(-1, 1)
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