Pandas 单元测试:如何断言 NaT 和 NaN 值相等?

Pandas unit testing: How to assert equality of NaT and NaN values?

在 NumPy 和 Pandas、nan != nanNaT != NaT 中。因此,在单元测试期间比较结果时,我如何断言返回值是这些值之一?一个简单的 assertEqual 自然会失败,即使我使用 pandas.util.testing.

在 python2.7 上测试,我得到以下结果

import numpy as np
import pandas as pd

x = np.nan
x is np.nan #True
x is pd.NaT #False
np.isnan(x) #True
pd.isnull(x) #True

y = pd.NaT
y is np.nan #False
y is pd.NaT #True
np.isnan(y) #TypeError !!
pd.isnull(y) #True

您也可以使用

x != x #True for nan
y != y #True for NaT

但我不太喜欢这种风格,我永远无法说服自己相信它。

如果要比较标量,一种方法是使用 assertTrueisnull。例如,在 DataFrame 单元测试 (pandas/tests/test_frame.py) 中,您可以找到 tests such as this:

self.assertTrue(com.isnull(df.ix['c', 'timestamp']))

compandas/core/common.py 的别名,因此 com.isnull 调用与 pd.isnull 相同的底层函数。)

另一方面,如果您将 Series 或 DataFrames 与 null 值进行相等性比较,这些将由 tm.assert_series_equaltm.assert_frame_equal 自动处理。例如:

>>> import pandas.util.testing as tm
>>> df = pd.DataFrame({'a': [1, np.nan]})
>>> df
    a
0   1
1 NaN

通常,NaN不等于NaN

>>> df == df
       a
0   True
1  False

但是 assert_frame_equalNaN 处理为等于自身:

>>> tm.assert_frame_equal(df, df)
# no AssertionError raised

在进行 assert_frame_equal 检查之前,您可以参考 .fillna() method on the dataframes to replace the null values with something else that won't otherwise appear in your values. You may also want to read these examples 如何使用 .fillna() 方法。