使用Numpy将2D数组值替换3D数组子数组中的1值问题求助
Got it, let's solve this problem cleanly and efficiently using pure NumPy—no messy loops that cause index errors or slow things down. Here's how to do it step by step:
The Core Idea
We need to target the subarray arr[:, 2:, 2:], find all positions where the value is 1, and replace those with the corresponding values from the values array. The key is to use NumPy's vectorized operations instead of Python loops, which are both faster and less error-prone.
Step-by-Step Implementation
Convert
valuesto a NumPy array (for easier vectorized handling):import numpy as np # Your original input arrays arr = np.array([[[0., 1., 43., 25., 21.], [0., 0., 0., 0., 0.], [0., 43., 0., 1., 0.], [0., 43., 1., 0., 1.], [0., 45., 0., 1., 0.]], [[0., 1., 38., 29., 46.], [0., 0., 0., 0., 0.], [0., 32., 0., 0., 1.], [0., 26., 0., 0., 1.], [0., 30., 1., 1., 0.]]]) values = np.array([[2, 3, 1, 4], [4, 1, 5, 9]])Create a mask for the target subarray (identifies where values are
1):target_subarray = arr[:, 2:, 2:] mask = target_subarray == 1This mask has the same shape as
target_subarray((2, 3, 3)in your example), withTruewherever the value is1.Replace the matched values using the mask:
# Flatten the values array to match the flattened mask indices target_subarray[mask] = values.flatten()NumPy automatically aligns the flattened
valueswith the flattened positions wheremaskisTrue, preserving the per-sample order of replacements.
Verify the Result
If you print arr now, you'll get exactly your expected output:
print(arr) # Output: # [[[ 0. 1. 43. 25. 21.] # [ 0. 0. 0. 0. 0.] # [ 0. 43. 0. 2. 0.] # [ 0. 43. 3. 0. 1.] # [ 0. 45. 0. 4. 0.]] # # [[ 0. 1. 38. 29. 46.] # [ 0. 0. 0. 0. 0.] # [ 0. 32. 0. 0. 4.] # [ 0. 26. 0. 0. 1.] # [ 0. 30. 5. 9. 0.]]]
Why Your Original Code Failed
- You used
==instead of=for assignment (a common typo!). - Your loop tried to assign entire rows of
valuesto all indices at once, which caused dimension mismatches and index errors. - Using
argwhereand loops is unnecessary here—NumPy's mask-based indexing handles this in a single vectorized operation, which is far more efficient (especially for large arrays).
Efficiency Note
This approach uses NumPy's optimized C-backed operations instead of Python loops, so it will be orders of magnitude faster than any loop-based solution when working with large arrays.
内容的提问来源于stack exchange,提问作者Carlos Eduardo Corpus

