Extracting specific columns in numpy array
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Extracting Specific Columns In Numpy Array
00:29 Accepted Answer Score 392
00:52 Answer 2 Score 38
01:03 Answer 3 Score 18
01:20 Answer 4 Score 11
01:38 Thank you
--
Full question
https://stackoverflow.com/questions/8386...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #syntax #numpy
#avk47
    Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Extracting Specific Columns In Numpy Array
00:29 Accepted Answer Score 392
00:52 Answer 2 Score 38
01:03 Answer 3 Score 18
01:20 Answer 4 Score 11
01:38 Thank you
--
Full question
https://stackoverflow.com/questions/8386...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #syntax #numpy
#avk47
ACCEPTED ANSWER
Score 392
I assume you wanted columns 1 and 9?
To select multiple columns at once, use
X = data[:, [1, 9]]
To select one at a time, use
x, y = data[:, 1], data[:, 9]
With names:
data[:, ['Column Name1','Column Name2']]
You can get the names from data.dtype.names…
ANSWER 2
Score 38
Assuming you want to get columns 1 and 9 with that code snippet, it should be:
extractedData = data[:,[1,9]]
ANSWER 3
Score 18
if you want to extract only some columns:
idx_IN_columns = [1, 9]
extractedData = data[:,idx_IN_columns]
if you want to exclude specific columns:
idx_OUT_columns = [1, 9]
idx_IN_columns = [i for i in xrange(np.shape(data)[1]) if i not in idx_OUT_columns]
extractedData = data[:,idx_IN_columns]
ANSWER 4
Score 11
One thing I would like to point out is, if the number of columns you want to extract is 1 the resulting matrix would not be a Mx1 Matrix as you might expect but instead an array containing the elements of the column you extracted.
To convert it to Matrix the reshape(M,1) method should be used on the resulting array.