Python中输出numpy数组含非零元素的行号报错,求解决
问题:提取NumPy数组中包含至少一个非零元素的行号
原代码及错误信息
原代码
import numpy as np out = np.array([[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 423.81345923, 0. , 407.01354328, 419.14952534, 0. , 212.13245959, 0. , 0. , 0. , 0. , 0. ], [402.93473651, 0. , 216.08166277, 407.01354328, 0. , 414.17017965, 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]]) for i in range(0,len(out)): if (out[i]==0): print(i) else: print("None")
错误信息
in <module> if (out[i]==0): ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
期望输出
[1,2]
错误原因
out[i]==0会返回一个与该行长度相同的布尔数组,直接将这个数组作为if的判断条件时,NumPy无法确定你要判断所有元素都为0还是至少一个元素为0,因此抛出歧义错误。
解决方法
方法1:使用NumPy向量化操作(推荐)
利用NumPy的内置函数实现高效的行判断,无需循环:
import numpy as np out = np.array([[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 423.81345923, 0. , 407.01354328, 419.14952534, 0. , 212.13245959, 0. , 0. , 0. , 0. , 0. ], [402.93473651, 0. , 216.08166277, 407.01354328, 0. , 414.17017965, 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]]) # 按行判断是否存在非零元素,返回布尔数组 has_non_zero = np.any(out != 0, axis=1) # 获取布尔数组中True对应的行号,转为列表 non_zero_rows = np.where(has_non_zero)[0].tolist() print(non_zero_rows) # 输出: [1, 2]
np.any(out != 0, axis=1):axis=1指定按行计算,判断每行是否至少有一个非零元素,返回布尔数组[False, True, True, False]np.where(has_non_zero):提取布尔数组中True对应的索引,再通过.tolist()转为普通列表。
方法2:修复原循环代码
如果坚持使用循环,需要在判断时明确使用np.any():
import numpy as np out = np.array([[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 423.81345923, 0. , 407.01354328, 419.14952534, 0. , 212.13245959, 0. , 0. , 0. , 0. , 0. ], [402.93473651, 0. , 216.08166277, 407.01354328, 0. , 414.17017965, 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]]) non_zero_rows = [] for i in range(len(out)): # 判断当前行是否有至少一个非零元素 if np.any(out[i] != 0): non_zero_rows.append(i) print(non_zero_rows) # 输出: [1, 2]
内容的提问来源于stack exchange,提问作者AEinstein
相关产品推荐
相关产品推荐

