【问题标题】:Copied array is being affected by changing the original array in python复制的数组受到更改 python 中的原始数组的影响
【发布时间】:2019-09-29 12:13:46
【问题描述】:

jupyter notebook python 中,当我更改作为另一个数组副本的数组值时,它会影响原始数组。这不方便给我用。

我在 jupyter 笔记本上尝试过以下代码,我正在更改 arr_temp[1] 数组的值。但它会影响 原始 numpy 数组 .

import numpy as np
array = np.array([1,5,6,7,8,94])
array[4:6]
arr_temp = array[4:6]
arr_temp[1]=100
array

我期待array([ 1, 5, 6, 7, 8, 94]),但我得到的值是array([ 1, 5, 6, 7, 8, 100])

【问题讨论】:

    标签: python arrays numpy jupyter-notebook


    【解决方案1】:

    尝试使用arr_temp = array[4:6].copy()。 当您想要更改数据的子集时,您应该始终使用 copy(),否则 python 会将其视为切片并更改新对象和原始对象。

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 2013-05-09
      • 1970-01-01
      • 2021-04-01
      • 2020-08-09
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多