How to access the ith column of a NumPy multidimensional array? How to access the ith column of a NumPy multidimensional array? python python

# How to access the ith column of a NumPy multidimensional array?

``>>> test[:,0]array([1, 3, 5])``

Similarly,

``>>> test[1,:]array([3, 4])``

lets you access rows. 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.

And if you want to access more than one column at a time you could do:

``>>> test = np.arange(9).reshape((3,3))>>> testarray([[0, 1, 2],       [3, 4, 5],       [6, 7, 8]])>>> test[:,[0,2]]array([[0, 2],       [3, 5],       [6, 8]])``

``>>> 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[:,]array([,       ,       ])``

gives you a column vector, so that you can do concatenate or hstack operation.

e.g.

``>>> np.hstack((test, test[:,]))array([[1, 2, 1],       [3, 4, 3],       [5, 6, 5]])``