【问题标题】:Modify numpy array inside a function修改函数内的numpy数组
【发布时间】:2021-09-24 15:28:03
【问题描述】:

我想修改传递给函数的numpy 数组。解决方案应该修改它的形状而不需要返回它。

例如,以下内容可以正常工作和打印[3,4]

a = np.array([1,2])
b = np.array([-1,-2])
def foo(a,b):
    b[:] = a+2
foo(a,b)
print(b)

我感兴趣的是形状不匹配的情况。例如,以下给出错误 'ValueError: could not broadcast input array from shape (2,2) into shape (2,)'

def foo2(a,b):
    b[:] = np.outer(b,a)
foo2(a,b)

如何修改函数foo2来改变b的内容?

foo2(a,b) 之后,print(b) 应该打印出来

[[3 6]
 [4 8]]

【问题讨论】:

  • np.outer 返回的是 2*2 数组,你想把它分配给 2*1 数组。这就是问题
  • 数组的形状和数据类型不能就地改变。有几个例外,b.shape=(3,4)b.resize(3,4),但它们的使用受到限制,不适用于您的情况。
  • 一些ufuncouter 采用out 参数,但它的形状必须以正确的开头。
  • 是的,我的兴趣正是在形状不匹配时如何做这种事情。

标签: python arrays numpy pass-by-reference


【解决方案1】:

你的形状有问题。但我仍然尝试了一些可行的方法。

def foo2(a,b):
    b = b.astype(dtype=object)
    x = np.outer(b,a)
    b[0] = x[0].astype(int)
    b[1] = x[1].astype(int)
    b = np.concatenate(b).reshape(x.shape)
    print(b)
foo2(a,b)

【讨论】:

    猜你喜欢
    • 2013-02-18
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多