python - 查找包含 'inf' 或 'nan' 的项目的索引

标签 python list numpy indexing

以下是我的列表中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]])

其中一些项目包含 infnan 值。因此,我试图返回包含此类值的项目的索引。因此我尝试执行以下操作:

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 项。由于它包含 infnan,我想返回该项目的索引。该项目基本上是一个列表的列表。

谢谢。

最佳答案

按照@coldspeed的建议,您可以获得包含infs或nans的元素的索引作为

idx = [i for i, arr in enumerate(f) if not np.isfinite(arr).all()]

来自 idx.append(f.index(x)) 的问题会导致您的错误。如果xf的第一个元素,它将返回True,否则抛出错误。如果您设置 f[0] = x.copy() 并尝试检查 f 中的 x,它也会抛出错误。两者都是由于 bool(x == x) 定义不明确所致。

关于python - 查找包含 'inf' 或 'nan' 的项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48592885/

相关文章:

python - 服务器可以发布广播消息来终止工作人员吗?兔子MQ

python - 如何防止启动 Tkinter 时出现两个根窗口?

list - 了解Scala中的infix方法调用和cons运算符(::)

python - 如何在 Python 中的列表上编写索引循环?

python - 连接两个具有交错列的矩阵

python - 使用 re.match() 查找子字符串

python - 为什么 python 中的打印格式化程序不完全相同?

Java 数组列表栈

python - numpy中任意函数的按行广播

python - 通过 multiprocessing.Queue 传递 numpy 数组