pandas 如何在unittest中使用assert_frame_equal

9fkzdhlc  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(125)

新的unittest包。我试图通过以下代码验证函数返回的DataFrame。即使我硬编码assert_frame_equal的输入为相等(pd.DataFrame([0,0,0,0])),unittest仍然失败。有人愿意解释为什么会发生这种情况吗?

import unittest
from pandas.util.testing import assert_frame_equal
class TestSplitWeight(unittest.TestCase):
    def test_allZero(self):
        #splitWeight(pd.DataFrame([0,0,0,0]),10)
        self.assert_frame_equal(pd.DataFrame([0,0,0,0]),pd.DataFrame([0,0,0,0]))

suite = unittest.TestLoader().loadTestsFromTestCase(TestSplitWeight)
unittest.TextTestRunner(verbosity=2).run(suite)

个字符

jgwigjjp

jgwigjjp1#

alecxe的回答是不完整的,你确实可以使用pandas的assert_frame_equal()unittest.TestCase,使用unittest.TestCase.addTypeEqualityFunc

import unittest
import pandas as pd
import pandas.testing as pd_testing

class TestSplitWeight(unittest.TestCase):
    def assertDataframeEqual(self, a, b, msg):
        try:
            pd_testing.assert_frame_equal(a, b)
        except AssertionError as e:
            raise self.failureException(msg) from e

    def setUp(self):
        self.addTypeEqualityFunc(pd.DataFrame, self.assertDataframeEqual)

    def test_allZero(self):
        self.assertEqual(pd.DataFrame([0,0,0,0]), pd.DataFrame([0,0,0,0]))

字符串

4smxwvx5

4smxwvx52#

assert_frame_equal()来自pandas.testing包,而不是unittest.TestCase类。替换:

self.assert_frame_equal(pd.DataFrame([0,0,0,0]),pd.DataFrame([0,0,0,0]))

字符串
使用:

assert_frame_equal(pd.DataFrame([0,0,0,0]), pd.DataFrame([0,0,0,0]))


当您有self.assert_frame_equal时,它试图在unittest.TestCase示例上查找assert_frame_equal属性,由于unittest.TestCase类上没有暴露assert_frame_equal属性或方法,因此它引发了AttributeError

k5hmc34c

k5hmc34c3#

如果你导入这个,问题就解决了。

from pandas.testing import assert_frame_equal  # <-- for testing dataframes

字符串

相关问题