Unpack NumPy array by column

北慕城南 提交于 2019-12-19 05:14:50

问题


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.


回答1:


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.




回答2:


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))



回答3:


I guess numpy.split will not suffice in the future. Instead, it should be

my_func(tuple(numpy.split(array, 3, 1)))

Currently, python prints the following warning:

FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be interpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.



来源:https://stackoverflow.com/questions/27046533/unpack-numpy-array-by-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!