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

如何用NumPy将矩阵中含0元素的行全部置为0?

Solution to Zero-out Rows Containing Zero in a 3D NumPy Array

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 of a == 0 to avoid precision issues.
  • The axis=-1 parameter ensures we check along the innermost dimension (the "rows" you're targeting) regardless of the array's overall shape.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:14:38