如何用NumPy将矩阵中含0元素的行全部置为0?
Got it, let's work through this problem step by step. You have a 3D NumPy array where you want to zero out any row (the innermost 1D subarrays) that contains at least one zero. Here's how to do it:
Step 1: Initialize your target array
First, let's create the exact array you described (since the random function would generate different values):
import numpy as np a = np.array([[[1, 0], [1, 1]], [[1, 1], [1, 0]]])
Step 2: Identify rows with zero elements
We need to check each innermost row (shape (2,)) to see if it contains any zero. Using np.any() along the last axis (axis=-1) will give us a boolean matrix where True marks rows that have at least one zero:
# Check each row for presence of zero has_zero = np.any(a == 0, axis=-1)
This has_zero array will look like:
[[ True False] [False True]]
Step 3: Zero out the identified rows
Use NumPy's boolean indexing to directly set all rows marked as True to zero:
# Assign zero to rows that contain any zero a[has_zero] = 0
Final Result
If you print the modified array, you'll get exactly your expected output:
print(a)
Output:
[[[0 0] [1 1]] [[1 1] [0 0]]]
Key Notes
- If your array had floating-point values (instead of integers), use
np.isclose(a, 0)instead ofa == 0to avoid precision issues. - The
axis=-1parameter ensures we check along the innermost dimension (the "rows" you're targeting) regardless of the array's overall shape.
内容的提问来源于stack exchange,提问作者slimboy

