【问题标题】:How to replace an element of a replicate array without disturbing the original one?如何在不干扰原始数组的情况下替换复制数组的元素?
【发布时间】:2019-10-28 13:27:56
【问题描述】:

我是 python 的新手,这让我困惑了一段时间。

我写了下面的代码:

pool = np.array([[1,1],[1,1]])

def ringDisc(data):
    data_new = data
    data_new[1] = 0
    return data_new

print(pool)
print(ringDisc(pool))
print(pool)

我希望第一个“打印”的结果应该是[[1,1],[1,1]],第二个“打印”的结果应该是[[1,1],[0,0]],最后一个是[[1,1],[1,1]]

但我从中得到的是[[1,1],[1,1]]; [[1,1],[0,0]]; [[1,1],[0,0]]

谁能帮我解决这个问题并解释为什么我的代码没有按我想要的方式运行?非常感谢!

【问题讨论】:

  • 对于“为什么会发生这种情况”(这不是很直观,实际上是一个非常复杂的问题):stackoverflow.com/questions/11585793/…
  • 在 python 中,pooldatadata_new 都引用同一个对象。没有一个步骤可以复制。

标签: python numpy


【解决方案1】:

您可以执行以下操作:

data_new = np.copy(data)

内部ringDisc

所以有了这个改变,代码看起来像这样:

import numpy as np

pool = np.array([[1, 1], [1, 1]])


def ringDisc(data):
    data_new = np.copy(data)
    data_new[1] = 0
    return data_new


print(pool)
print(ringDisc(pool))
print(pool)

结果:

[[1 1], [1 1]]
[[1 1], [0 0]]
[[1 1], [1 1]]

正如预期的那样。

【讨论】:

  • 没问题!很高兴这对您有所帮助。
  • @Veronica 如果这解决了您的问题,请考虑通过单击相应答案旁边的“勾选”按钮来接受此答案或任何其他解决了您问题的答案。
【解决方案2】:

在 numpy 视图中和副本是两个不同的概念,在您的情况下,您想要修改数据的副本。 An interesting article about that.

正如@Rafael 所说,您可以这样做。

pool = np.array([[1,1],[1,1]])

def ringDisc(data):
    data_new = np.copy(data) # <===== Here 
    data_new[1] = 0
    return data_new

print(pool)
print(ringDisc(pool))
print(pool)

【讨论】:

  • @GPhilo 当我写了这个遮阳篷时,现有的代码还没有! @Rafael 只将 data_new = np.copy(data) 作为一个awser。我也赞成它的awser。
猜你喜欢
  • 2020-06-26
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2021-12-02
  • 2021-12-14
相关资源
最近更新 更多