比较包含NaN的numpy数组

比较包含NaN的numpy数组

本文介绍了比较包含NaN的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的单元测试,我想检查两个数组是否相同.简化示例:

For my unittest, I want to check if two arrays are identical. Reduced example:

a = np.array([1, 2, np.NaN])
b = np.array([1, 2, np.NaN])
if np.all(a==b):
    print 'arrays are equal'

这不起作用,因为nan != nan.最好的进行方法是什么?

This does not work because nan != nan.What is the best way to proceed?

推荐答案

或者,您也可以使用 numpy.testing.assert_equal numpy.testing.assert_array_equal try/except:

Alternatively you can use numpy.testing.assert_equal or numpy.testing.assert_array_equal with a try/except:

In : import numpy as np

In : def nan_equal(a,b):
...:     try:
...:         np.testing.assert_equal(a,b)
...:     except AssertionError:
...:         return False
...:     return True

In : a=np.array([1, 2, np.NaN])

In : b=np.array([1, 2, np.NaN])

In : nan_equal(a,b)
Out: True

In : a=np.array([1, 2, np.NaN])

In : b=np.array([3, 2, np.NaN])

In : nan_equal(a,b)
Out: False

修改

由于您正在使用它进行单元测试,因此裸露的assert(而不是将其包装成True/False)可能会更自然.

Since you are using this for unittesting, bare assert (instead of wrapping it to get True/False) might be more natural.

这篇关于比较包含NaN的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 03:01