当元素小于0.2时替换3D NumPy数组中的2D子数组
Let's break this down clearly. First, let's confirm the requirement: we have a 3D array a of shape (3,3,3), and whenever any element in a 2D subarray (each of the 3x3 slices along the first axis, which are the natural 2D components here) is less than 0.2, we need to replace that entire 2D subarray. I'll use replacing with all zeros as an example, but you can swap this for any value you need.
Step 1: Set up the original array
First, let's define your array properly (since using np.random.rand would generate different values, we'll use the exact array you provided):
import numpy as np # Your provided 3D array a = np.array([ [[0.04331462, 0.30333583, 0.37462236], [0.30225757, 0.35859228, 0.57845153], [0.49995805, 0.3539933, 0.11172398]], [[0.28983508, 0.31122743, 0.67818926], [0.42720309, 0.24416101, 0.5469823 ], [0.22894097, 0.76159389, 0.80416832]], [[0.25661154, 0.64389696, 0.37555374], [0.87871659, 0.27806621, 0.3486518 ], [0.26388296, 0.8993144, 0.7857116 ]] ])
Step 2: Identify which 2D subarrays need replacement
We'll create a boolean mask that flags each 2D subarray (along the first axis) if it contains any element < 0.2:
# Check each 3x3 subarray for elements < 0.2 # axis=(1,2) collapses the last two dimensions to check the whole 2D slice mask = (a < 0.2).any(axis=(1, 2))
This mask will be a 1D array of shape (3,), where each value is True if the corresponding 2D subarray needs to be replaced. For your array, mask will be [True, False, False] since only the first subarray has elements < 0.2.
Step 3: Replace the flagged subarrays
Now we can replace those subarrays with your desired value (here, all zeros):
# Replace marked subarrays with all zeros a[mask] = 0 # If you want to replace with a specific value (e.g., 1), use: # a[mask] = np.full((3, 3), 1)
Step 4: Verify the result
Printing the array will show that the first 3x3 subarray is now all zeros, while the other two remain unchanged:
print(a)
Notes if your "2D subarray" refers to a different axis
If you meant 2D slices along a different axis (e.g., along the second axis, shape (3,3)), adjust the mask and indexing:
- For slices along the second axis:
mask = (a < 0.2).any(axis=(0, 2)) a[:, mask, :] = 0 - For slices along the third axis:
mask = (a < 0.2).any(axis=(0, 1)) a[:, :, mask] = 0
内容的提问来源于stack exchange,提问作者slimboy

