在单元测试一些函数的上下文中,我试图使用 python pandas建立2个DataFrame的相等性: ipdb expect 1 22012-01-01 00:00:00+00:00 NaN 32013-05-14 12:00:00+00:00 3 NaNipdb dfidentifier 1 2timestamp2012-01-01 00:00:00+00:00
ipdb> expect 1 2 2012-01-01 00:00:00+00:00 NaN 3 2013-05-14 12:00:00+00:00 3 NaN ipdb> df identifier 1 2 timestamp 2012-01-01 00:00:00+00:00 NaN 3 2013-05-14 12:00:00+00:00 3 NaN ipdb> df[1][0] nan ipdb> df[1][0], expect[1][0] (nan, nan) ipdb> df[1][0] == expect[1][0] False ipdb> df[1][1] == expect[1][1] True ipdb> type(df[1][0]) <type 'numpy.float64'> ipdb> type(expect[1][0]) <type 'numpy.float64'> ipdb> (list(df[1]), list(expect[1])) ([nan, 3.0], [nan, 3.0]) ipdb> df1, df2 = (list(df[1]), list(expect[1])) ;; df1 == df2 False
鉴于我正试图测试整个df的整体预期,包括NaN的位置,我做错了什么?
比较包含NaN的Series / DataFrame的相等性的最简单方法是什么?
您可以将assert_frame_equals与check_names = False一起使用(以便不检查索引/列名称),如果它们不相等则会引发:In [11]: from pandas.testing import assert_frame_equal In [12]: assert_frame_equal(df, expected, check_names=False)
你可以将它包装在一个函数中,例如:
try: assert_frame_equal(df, expected, check_names=False) return True except AssertionError: return False
在最近的大熊猫中,此功能已添加为.equals
:
df.equals(expected)