views:

823

answers:

2

does anybody know how do to extract a column from a multidimentional array in python..

+2  A: 

Could it be that you're using a NumPy array? Python has the array module, but that does not support multi-dimensional arrays. Normal Python lists are single-dimensional too.

However, if you have a simple two-dimensional list like this:

A = [[1,2,3,4],
     [5,6,7,8]]

then you can extract a column like this:

def column(matrix, i):
    return [row[i] for row in matrix]

Extracting the second column (index 1):

>>> column(A, 1)
[2, 6]
Martin Geisler
+2  A: 

The itemgetter operator can help too, if you like map-reduce style python, rather than list comprehensions, for a little variety!

# tested in 2.4
from operator import itemgetter
def column(matrix,i):
    f = itemgetter(i)
    return map(f,matrix)

M = [range(x,x+5) for x in range(10)]
assert column(M,1) == range(1,11)
Gregg Lind
use itertools.imap for large data
Reef