Reputation: 7826
New to python. I have a matrix likes:
[['A', 'A', 'A', 'A'],
['B', 'Z', 'A', 'A'],
['0', 'B', 'A', 'A'],
['0', 'C', 'A', 'A']
]
Now how can I access the specific column ?
likes [A B 0 0]
[A Z B C]
Thanks!
Upvotes: 0
Views: 204
Reputation: 69182
To get a single column you can do (if x
is your original array):
x_0 = [r[0] for r in x]
or if you do this a lot and can use numpy, it would look like this:
y = np.array(x)
y_0 = y[:,0]
An advantage of this approach over using zip
and/or dstack
is that there is minimal copying of data.
Upvotes: 1
Reputation: 107287
You can use zip
built-in function to get the columns of an array :
>>> a=[['A', 'A', 'A', 'A'],
... ['B', 'Z', 'A', 'A'],
... ['0', 'B', 'A', 'A'],
... ['0', 'C', 'A', 'A']
... ]
>>>
>>> zip(*a)
[('A', 'B', '0', '0'), ('A', 'Z', 'B', 'C'), ('A', 'A', 'A', 'A'), ('A', 'A', 'A', 'A')]
Or if you have a matrix in numpy
you can use dstack
:
>>> import numpy as np
>>> a=np.array([['A', 'A', 'A', 'A'],['B', 'Z', 'A', 'A'],['0', 'B', 'A', 'A'],['0', 'C', 'A', 'A']])
>>> np.dstack(a)
array([[['A', 'B', '0', '0'],
['A', 'Z', 'B', 'C'],
['A', 'A', 'A', 'A'],
['A', 'A', 'A', 'A']]],
dtype='|S1')
Also you can just use indexing to get a specific column :
>>> a[:,0]
array(['A', 'B', '0', '0'],
dtype='|S1')
Upvotes: 1
Reputation: 63707
If you need to access a 2D matrix column wise, you have to transpose the matrix such that the columns can be accessed as rows. Python's zip builtin can be used for matrix transpose.
>>> zip(*mat)[0]
('A', 'B', '0', '0')
On the contrary, you are using a numpy array (recommended if you are performing an extended matrix manipulation), and use numpy indexing. This would be natural
>>> import numpy as np
>>> npmat = np.asarray(mat)
>>> npmat[:,0]
array(['A', 'B', '0', '0'],
dtype='|S1')
based on your requirement, you can either transpose the entire matrix using numpy.dstack (if you are using numpy) or use zip to transpose before indexing column wise
>>> np.dstack(mat)
array([[['A', 'B', '0', '0'],
['A', 'Z', 'B', 'C'],
['A', 'A', 'A', 'A'],
['A', 'A', 'A', 'A']]],
dtype='|S1')
Upvotes: 2