python - 如何将assertSequenceEqual与pandas系列一起使用?

标签 python pandas python-unittest

我想使用 unittest 模块检查两个 pandas.Series 对象是否具有相同的内容:

    self.assertSequenceEqual(
        df['some_column'],
        someOtherSeries)

根据 unittest 文档,上述内容应该有效(基于 the docs )。但是,当我运行上述单元测试时,我得到以下结果:

======================================================================
ERROR: test_my_test (my_module.test.test_my_module.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/root/src/my_module/my_module/test/test_my_test.py", line 28, in test_my_test
    someOtherSeries)
  File "/usr/local/lib/python2.7/unittest/case.py", line 663, in assertSequenceEqual
    if seq1 == seq2:
  File "/usr/local/lib/python2.7/site-packages/pandas/core/generic.py", line 917, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

如何测试Series是否相同?

请注意,将 Series 转换为 list 对象似乎可以解决此问题,但感觉像是一种黑客攻击:

    self.assertSequenceEqual(
        list(df['some_column']),
        list(someOtherSeries))

最佳答案

请注意,df['some_column'].values 是一个 numpy 数组。要测试 numpy 数组的相等性(o 等价性),您可以使用 numpy.testing :

from numpy import testing

testing.assert_array_equal(df['some_column'].values, someOtherSeries.values)

如果数组是浮点型,则应考虑 numpy.testing.assert_almost_equal

testing.assert_almost_equal(df['some_column'].values, someOtherSeries.values)

因为直接等于 float 是有问题的。

关于python - 如何将assertSequenceEqual与pandas系列一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036136/

相关文章:

python - 根据某些条件过滤数据

python - 使用带有 DateTimeIndex 项的 select 从 HDFStore 检索 Pandas DataFrame 时缺少一个值

Python 测试多个子类的继承

python - 在单元测试 CI 期间模拟单击 PyQt5 QMessageBox 小部件中的按钮

python - pip,代理认证和 "Not supported proxy scheme"

python - 在ubuntu opencv python中运行代码后,网络摄像头一次又一次停止

python - pandas.Series.apply 中的访问索引

python - 导入错误 : cannot import name wraps

python - 如何获取Tesseract ocr检索到的字母坐标

python - PyPDF2 writer 函数创建空白页面