Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you extract a column from a multi-dimensional array?

>>> import numpy as np
>>> A = np.array([[1,2,3,4],[5,6,7,8]])

>>> A
array([[1, 2, 3, 4],
    [5, 6, 7, 8]])

>>> A[:,2] # returns the third columm
array([3, 7])

See also: "numpy.arange" and "reshape" to allocate memory

Example: (Allocating a array with shaping of matrix (3x4))

nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)

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]

Or alternatively, simply:

>>> [row[1] for row in A]
[2, 6]

If you have an array like

a = [[1, 2], [2, 3], [3, 4]]

Then you extract the first column like that:

[row[0] for row in a]

So the result looks like this:

[1, 2, 3]

check it out!

a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]

it is the same thing as above except somehow it is neater the zip does the work but requires single arrays as arguments, the *a syntax unpacks the multidimensional array into single array arguments


>>> x = arange(20).reshape(4,5)
>>> x array([[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]])

if you want the second column you can use

>>> x[:, 1]
array([ 1,  6, 11, 16])

def get_col(arr, col):
    return map(lambda x : x[col], arr)

a = [[1,2,3,4], [5,6,7,8], [9,10,11,12],[13,14,15,16]]

print get_col(a, 3)

map function in Python is another way to go.