簡體   English   中英

Numpy 子數組影響原始二維數組

[英]Numpy subarray affect the original 2d array

我用numpy創建了這個2D array

>>>import numpy as np
>>>np.random.seed(0)
>>>x2 = np.random.randint(10, size=(3, 4))
>>>print(x2)
[[5 0 3 3]
 [7 9 3 5]
 [2 4 7 6]]

然后我從x2創建了另一個子數組

>>>x2_sub = x2[:2, :2]
>>>print(x2_sub)
[[5 0]
 [7 9]]

現在如果我修改這個子數組,原來的數組就會改變:!:

>>>x2_sub[0, 0] = 99
>>>print(x2_sub)
[[99 0]
 [7 9]]
>>>print(x2)
[[99  0  3  3]
 [ 7  9  3  5]
 [ 2  4  7  6]]

我不想改變原始數組。 誰能告訴我我在做什么?

numpy 中的切片創建與 Python 列表不同的視圖 使用.copy()顯式創建副本:

x2_sub = x2[:2, :2].copy()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM