Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack NumPy array by column

If I have a NumPy array, for example 5x3, is there a way to unpack it column by column all at once to pass to a function rather than like this: my_func(arr[:, 0], arr[:, 1], arr[:, 2])?

Kind of like *args for list unpacking but by column.

like image 350
jeff_new Avatar asked Nov 20 '14 18:11

jeff_new


People also ask

Can you unpack Numpy array?

To unpack elements of a uint8 array into a binary-valued output array, use the numpy. unpackbits() method in Python Numpy. The result is binary-valued (0 or 1). The axis is the dimension over which bit-unpacking is done.


2 Answers

You can unpack the transpose of the array in order to use the columns for your function arguments:

my_func(*arr.T) 

Here's a simple example:

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

Let's write a function to add the columns together (normally done with x.sum(axis=1) in NumPy):

def add_cols(a, b, c):     return a+b+c 

Then we have:

>>> add_cols(*x.T) array([15, 18, 21, 24, 27]) 

NumPy arrays will be unpacked along the first dimension, hence the need to transpose the array.

like image 192
Alex Riley Avatar answered Sep 25 '22 21:09

Alex Riley


numpy.split splits an array into multiple sub-arrays. In your case, indices_or_sections is 3 since you have 3 columns, and axis = 1 since we're splitting by column.

my_func(numpy.split(array, 3, 1)) 
like image 41
Stephanie Avatar answered Sep 23 '22 21:09

Stephanie