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

如何利用引导数组重排NumPy数组每行的列?

Solution: Use NumPy Advanced Indexing

To solve this problem, you can leverage NumPy's advanced indexing to efficiently map elements from main_arr to result using guide_arr as the position guide. Here's how to do it:

Step-by-Step Code Implementation

import numpy as np

main_arr = np.array([[3, 7, 4], [2, 5, 6]])
guide_arr = np.array([[2, 0, 1], [0, 2, 1]])
# Initialize result with the same data type as main_arr to avoid type mismatches
result = np.zeros(main_arr.shape, dtype=main_arr.dtype)

# Create row indices to pair with guide_arr's column indices
rows = np.arange(main_arr.shape[0])[:, np.newaxis]

# Perform the mapping using advanced indexing
result[rows, guide_arr] = main_arr

# Verify the result
if np.array_equal(result, np.array([[7, 4, 3], [2, 6, 5]])):
    print('success!')  # This will print "success!" when run

How It Works

The key is understanding how guide_arr defines the element mapping:

  • For every element main_arr[i, j], guide_arr[i, j] tells you the column index k where this element should live in result (i.e., result[i, k] = main_arr[i, j]).

Using advanced indexing here is efficient and avoids manual loops:

  • rows = np.arange(main_arr.shape[0])[:, np.newaxis] creates a column vector [[0], [1]], which broadcasts to match the shape of guide_arr ((2,3)).
  • result[rows, guide_arr] selects exactly the target positions in result for each element in main_arr. Assigning main_arr to these positions directly performs the required mapping in a vectorized (fast, optimized) way.

This approach perfectly aligns with your problem's requirements and produces the exact result you're looking for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:59:07