以下是我的列表中1 项的示例:
array([[ 1, 2, 3,
43, 83, 92],
[ 12, 54, 93,
23, 94, 83],
[ 23, inf, inf,
inf, inf, inf],
[ 83, 33, 33,
83, 13, 83],
[ 83, nan, 83,
73, 43, 43],
[ 43, 83, 93,
22, 83, 54],
[ 66, nan, 74,
84, 84, 75],
[ 74, 44, 65,
6, 9, 7],
[ 54, 9, 74,
754, 55, 74]])
其中一些项目包含 inf
或 nan
值。因此,我试图返回包含此类值的项目的索引。因此我尝试执行以下操作:
for x in f:
if float('inf') in x:
idx.append(f.index(x))
elif float('nan') in x:
idx.append(f.index(x))
但是,当我运行脚本时,出现以下错误:
idx.append(f.index(x))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是为什么呢?我该如何解决这个问题?
提醒,以上示例仅为1 项。由于它包含 inf
和 nan
,我想返回该项目的索引。该项目基本上是一个列表的列表。
谢谢。
最佳答案
按照@coldspeed的建议,您可以获得包含inf
s或nan
s的元素的索引作为
idx = [i for i, arr in enumerate(f) if not np.isfinite(arr).all()]
来自 idx.append(f.index(x))
的问题会导致您的错误。如果x
是f
的第一个元素,它将返回True
,否则抛出错误。如果您设置 f[0] = x.copy() 并尝试检查 f 中的 x,它也会抛出错误。两者都是由于 bool(x == x)
定义不明确所致。
关于python - 查找包含 'inf' 或 'nan' 的项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48592885/