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

Python实现NumPy数组全零行查找删除并记录对应行索引

NumPy移除全零行并记录索引实现

你可以按以下步骤实现需求,代码可直接运行得到你给出的期望结果:

  • 逐行扫描数组,标记所有元素全为0的行
  • 提取全零行对应的索引,合并到原有索引列表后按升序整理
  • 用反向掩码过滤数组,删除所有标记的全零行
import numpy as np

# 原始输入
A=np.array([[ 0.00000000e+00,  3.57765318e-08,  0.00000000e+00,
         1.74215085e-07,  0.00000000e+00,  0.00000000e+00,
         0.00000000e+00],
       [-1.06733099e-07,  0.00000000e+00,  0.00000000e+00,
         0.00000000e+00,  3.50573100e-08,  0.00000000e+00,
         0.00000000e+00],
       [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
         0.00000000e+00],
       [-1.78530448e-07,  0.00000000e+00,  0.00000000e+00,
         0.00000000e+00,  1.61650808e-08,  9.06895783e-08,
         0.00000000e+00],
       [ 0.00000000e+00, -4.46583743e-08,  0.00000000e+00,
        -5.99482549e-08,  0.00000000e+00,  0.00000000e+00,
         1.04606629e-07],
       [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
        -9.64183682e-08,  0.00000000e+00,  0.00000000e+00,
         9.64183682e-08],
       [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
         0.00000000e+00, -1.25633650e-07, -4.03926936e-07,
         0.00000000e+00]])
B = [5,8]

# 生成全零行掩码:逐行判断是否所有元素为0
zero_row_mask = (A == 0).all(axis=1)
# 提取全零行索引,和原有B合并后升序排列,匹配期望输出格式
zero_row_indices = np.where(zero_row_mask)[0].tolist()
B = sorted(zero_row_indices + B)
# 过滤删除全零行
A = A[~zero_row_mask]

运行代码后得到的结果和预期完全一致:

  • 处理后的A为6行数组,原索引为2的全零行被成功移除
  • 索引列表B输出为[2,5,8]

注意:如果数组是数值计算得到的,浮点数可能存在精度误差,不会严格等于0,此时可以把判断条件替换为np.isclose(A, 0).all(axis=1),避免把极小的计算残差误判为0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:42:14