按列解压缩NumPy数组

jef*_*new 17 python arrays numpy argument-unpacking

如果我有一个NumPy的阵列,例如5×3,有没有办法把它解压到通过一次全部列接一列传递给一个函数,而不是像这样:my_func(arr[:, 0], arr[:, 1], arr[:, 2])

有点像*args列表拆包但是按列.

Ale*_*ley 26

您可以解压缩数组的转置,以便使用函数参数的列:

my_func(*arr.T)
Run Code Online (Sandbox Code Playgroud)

这是一个简单的例子:

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

让我们编写一个函数来将列添加到一起(通常x.sum(axis=1)在NumPy中完成):

def add_cols(a, b, c):
    return a+b+c
Run Code Online (Sandbox Code Playgroud)

然后我们有:

>>> add_cols(*x.T)
array([15, 18, 21, 24, 27])
Run Code Online (Sandbox Code Playgroud)

NumPy数组将沿第一维解压缩,因此需要转置数组.


小智 11

numpy.split将数组拆分为多个子数组.在你的情况下,indices_or_sections因为你有3列,axis = 1所以是3,因为我们按列拆分.

my_func(numpy.split(array, 3, 1))
Run Code Online (Sandbox Code Playgroud)