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

如何无需循环实现NumPy数组的指定索引批量赋值

Solution to Vectorize Your NumPy Indexing

Your initial attempt arr[idxs, idxs] =1 doesn't work because it selects diagonal elements (like (1,1), (4,4), (7,7)) instead of the full 3x3 block of rows and columns specified in idxs.

To replicate the loop's behavior without iterating, you can use NumPy's built-in tools to generate the correct index pairs efficiently:

Method 1: Using np.ix_ (Most Readable)

The np.ix_ function reshapes your index lists into compatible shapes for broadcasting, ensuring you select all combinations of rows and columns from idxs:

import numpy as np

arr = np.zeros((10, 10), dtype=np.int)
idxs = [1, 4, 7]

# Vectorized replacement for the loop
arr[np.ix_(idxs, idxs)] = 1

Method 2: Manual Broadcasting

You can also reshape the row indices into a column vector to trigger broadcasting with the column indices directly:

arr[np.array(idxs)[:, None], idxs] = 1

Why These Work

  • np.ix_(idxs, idxs) creates two arrays: a 3x1 row array and a 1x3 column array. When used together, they broadcast to a 3x3 grid of index pairs, exactly matching what your loop does.
  • np.array(idxs)[:, None] converts the 1D index list into a column vector. Pairing this with the original 1D column index list triggers the same broadcasting effect, selecting all rows in idxs at all columns in idxs.

Both methods skip explicit loops and use NumPy's optimized vector operations, which are faster and more idiomatic for NumPy-based code.

内容的提问来源于stack exchange,提问作者roger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:29:04