You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NumPy高级索引修改数组时,会创建何种副本?

Understanding NumPy Advanced Indexing: Copies vs In-Place Modification

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:

  1. Creates a boolean mask (tmp == val) using advanced indexing logic.
  2. Directly locates the positions in the original tmp array where the mask is True.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:56:25