Pandas 数据框值相等性测试

28

另一个Pandas问题!

我正在编写一些单元测试来测试两个数据帧是否相等,但是测试似乎没有查看数据帧的值,只有结构:

dates = pd.date_range('20130101', periods=6)

df1 = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
df2 = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))

print df1
print df2
self.assertItemsEqual(df1, df2)

我需要在断言相等之前将数据帧转换为另一种数据结构吗?

4个回答

44
啊,当然已经有解决方案了:
from pandas.util.testing import assert_frame_equal

编辑:pandas.util.testing在2020年已经弃用。从1.0版本开始,请使用:

from pandas.testing import assert_frame_equal

可以在这里找到关于 assert_frame_equal 的 API 文档 here


6

虽然assert_frame_equal在单元测试中很有用,但在分析过程中我发现以下方法也很有用,因为人们可能希望进一步检查哪些值不相等:df1.equals(df2)


4
此外,NumPy的实用程序也起作用:
import numpy.testing as npt

npt.assert_array_equal(df1, df2)

0
In [62]: import numpy as np

In [63]: import pandas as pd

In [64]: np.random.seed(30)

In [65]: df_old = pd.DataFrame(np.random.randn(4,5))

In [66]: df_old
Out[66]: 
          0         1         2         3         4
0 -1.264053  1.527905 -0.970711  0.470560 -0.100697
1  0.303793 -1.725962  1.585095  0.134297 -1.106855
2  1.578226  0.107498 -0.764048 -0.775189  1.383847
3  0.760385 -0.285646  0.538367 -2.083897  0.937782

In [67]: np.random.seed(30)

In [68]: df_new = pd.DataFrame(np.random.randn(4,5))

In [69]: df_new
Out[69]: 
          0         1         2         3         4
0 -1.264053  1.527905 -0.970711  0.470560 -0.100697
1  0.303793 -1.725962  1.585095  0.134297 -1.106855
2  1.578226  0.107498 -0.764048 -0.775189  1.383847
3  0.760385 -0.285646  0.538367 -2.083897  0.937782

In [70]: df_old.equals(df_new) #Equality check here, returns boolean expression: True/False
Out[70]: True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接