如何利用引导数组重排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 indexkwhere this element should live inresult(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 ofguide_arr((2,3)).result[rows, guide_arr]selects exactly the target positions inresultfor each element inmain_arr. Assigningmain_arrto 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
相关产品推荐
相关产品推荐

