使用NumPy高级索引修改数组时,会创建何种副本?
Great question—this is a common point of confusion when working with NumPy's advanced indexing, so let's break it down with clear examples.
First, let's recap the official rule you mentioned:
高级索引始终返回数据的副本(与返回视图的基础切片形成对比)。
This rule applies when you use advanced indexing to read/extract data into a new variable. Let's confirm with your first example:
import numpy as np tmp = np.array([0,0,0,1,1,1]) new = tmp[tmp == 0] # Advanced indexing returns a copy new[1] = 5 print(tmp) # Output: [0 0 0 1 1 1] — original array is untouched
Here, new is a separate copy of the elements where tmp == 0, so modifying new doesn't affect the original tmp.
What happens when you use advanced indexing to modify the original array?
Your second example is a different scenario: you're using advanced indexing as the target of an assignment, not extracting data into a new variable. Let's look at that code again:
tmp = np.array([0,0,0,12,12,12,4,5,4,4]) uni = np.unique(tmp) for idx, val in enumerate(uni): tmp[tmp == val] = idx # Assign directly to positions found via advanced indexing print(tmp) # Output: [0 0 0 1 1 1 2 3 2 2] — original array is modified
In this case, NumPy doesn't create a copy of the entire array. Instead, it:
- Creates a boolean mask (
tmp == val) using advanced indexing logic. - Directly locates the positions in the original
tmparray where the mask isTrue. - Updates those positions with the new value (
idx) in-place.
This is a key distinction to remember:
- Reading via advanced indexing: Returns a copy of the selected data.
- Assigning via advanced indexing: Operates directly on the original array's memory, no full copy is created.
The "returns a copy" rule only applies when you're retrieving data into a new variable—not when you're using the index to target elements for modification.
内容的提问来源于stack exchange,提问作者meTchaikovsky

