How do I access the ith column of a NumPy multidimensional array?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open
--
Chapters
00:00 How Do I Access The Ith Column Of A Numpy Multidimensional Array?
00:15 Accepted Answer Score 996
00:39 Answer 2 Score 93
00:53 Answer 3 Score 105
01:25 Answer 4 Score 25
01:34 Thank you
--
Full question
https://stackoverflow.com/questions/4455...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #numpy
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open
--
Chapters
00:00 How Do I Access The Ith Column Of A Numpy Multidimensional Array?
00:15 Accepted Answer Score 996
00:39 Answer 2 Score 93
00:53 Answer 3 Score 105
01:25 Answer 4 Score 25
01:34 Thank you
--
Full question
https://stackoverflow.com/questions/4455...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #numpy
#avk47
ACCEPTED ANSWER
Score 996
With:
test = np.array([[1, 2], [3, 4], [5, 6]])
To access column 0:
>>> test[:, 0]
array([1, 3, 5])
To access row 0:
>>> test[0, :]
array([1, 2])
This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.
ANSWER 2
Score 105
>>> test[:,0]
array([1, 3, 5])
this command gives you a row vector, if you just want to loop over it, it's fine, but if you want to hstack with some other array with dimension 3xN, you will have
ValueError: all the input arrays must have same number of dimensions
while
>>> test[:,[0]]
array([[1],
[3],
[5]])
gives you a column vector, so that you can do concatenate or hstack operation.
e.g.
>>> np.hstack((test, test[:,[0]]))
array([[1, 2, 1],
[3, 4, 3],
[5, 6, 5]])
ANSWER 3
Score 93
And if you want to access more than one column at a time you could do:
>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
[3, 5],
[6, 8]])
ANSWER 4
Score 25
You could also transpose and return a row:
In [4]: test.T[0]
Out[4]: array([1, 3, 5])