Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to access columns of an array in Python?

Tags:

python

arrays

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>

Addendum

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
like image 213
qazwsx Avatar asked Jan 17 '12 19:01

qazwsx


People also ask

How do you access parts of an array in Python?

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.

How do I separate an array of columns in Python?

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.

How do you access columns in a matrix?

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.


1 Answers

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

like image 108
Bruno Avatar answered Sep 17 '22 16:09

Bruno