In Matlab, one can access a column of an array with :
:
>> array=[1 2 3; 4 5 6]
array =
1 2 3
4 5 6
>> array(:,2)
ans =
2
5
How to do this in Python?
>>> array=[[1,2,3],[4,5,6]]
>>> array[:,2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>> array[:][2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
I'd like an example applied to an array of dimensions greater than three:
>> B = cat(3, eye(3), ones(3), magic(3))
B(:,:,1) =
1 0 0
0 1 0
0 0 1
B(:,:,2) =
1 1 1
1 1 1
1 1 1
B(:,:,3) =
8 1 6
3 5 7
4 9 2
>> B(:,:,1)
ans =
1 0 0
0 1 0
0 0 1
>> B(:,2,:)
ans(:,:,1) =
0
1
0
ans(:,:,2) =
1
1
1
ans(:,:,3) =
1
5
9
An array in Python is used to store multiple values or items or elements of the same type in a single variable. We can access elements of an array using the index operator [] . All you need do in order to access a particular element is to call the array you created.
The hsplit() function is used to split an array into multiple sub-arrays horizontally (column-wise). hsplit is equivalent to split with axis=1, the array is always split along the second axis regardless of the array dimension.
There are three ways to access the rows or columns of a matrix: through indexers, through row and column getter methods, and through enumerators. The indexer property is overloaded to allow for direct indexed access to complete or partial rows or columns. The indexers are similar to the indexers for vectors.
Use Numpy.
>>> import numpy as np
>>>
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a[:, 2]
array([3, 6])
If you come from Matlab, this should be of interest: http://www.scipy.org/NumPy_for_Matlab_Users
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With