按列解压缩NumPy数组 [英] Unpack NumPy array by column

查看:98
本文介绍了按列解压缩NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个NumPy数组,例如5x3,是否有一种方法可以一次一列地将其拆包以传递给函数,而不是像这样:my_func(arr[:, 0], arr[:, 1], arr[:, 2])?

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

类似于*args的列表解包方式,但按列.

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

推荐答案

您可以解开数组的转置,以便将列用作函数参数:

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

my_func(*arr.T)

这是一个简单的例子:

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

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

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

那么我们有:

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

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

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

这篇关于按列解压缩NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆