如何在单元测试中使用 pandas 数据框

问题描述 投票:0回答:3

我正在开发一组 Python 脚本来预处理数据集,然后使用 scikit-learn 生成一系列机器学习模型。我想开发一组单元测试来检查数据预处理功能,并且希望能够使用一个小型测试 pandas 数据框,我可以确定答案并在断言语句中使用它。

我似乎无法让它加载数据帧并使用 self 将其传递给单元测试。我的代码看起来像这样;

def setUp(self):
    TEST_INPUT_DIR = 'data/'
    test_file_name =  'testdata.csv'
    try:
        data = pd.read_csv(INPUT_DIR + test_file_name,
            sep = ',',
            header = 0)
    except IOError:
        print 'cannot open file'
    self.fixture = data

def tearDown(self):
    del self.fixture

def test1(self):    
    self.assertEqual(somefunction(self.fixture), somevalue)

if __name__ == '__main__':
    unittest.main()

感谢您的帮助。

python pandas python-unittest
3个回答
37
投票

Pandas 有一些用于测试的实用程序。

import unittest
import pandas as pd
from pandas.util.testing import assert_frame_equal # <-- for testing dataframes

class DFTests(unittest.TestCase):

    """ class for running unittests """

    def setUp(self):
        """ Your setUp """
        TEST_INPUT_DIR = 'data/'
        test_file_name =  'testdata.csv'
        try:
            data = pd.read_csv(INPUT_DIR + test_file_name,
                sep = ',',
                header = 0)
        except IOError:
            print 'cannot open file'
        self.fixture = data

    def test_dataFrame_constructedAsExpected(self):
        """ Test that the dataframe read in equals what you expect"""
        foo = pd.DataFrame()
        assert_frame_equal(self.fixture, foo)

33
投票

如果你使用的是最新的 pandas,我认为以下方式更干净一些:

import pandas as pd

pd.testing.assert_frame_equal(my_df, expected_df)
pd.testing.assert_series_equal(my_series, expected_series)
pd.testing.assert_index_equal(my_index, expected_index)

如果这些函数不“相等”,每个函数都会引发

AssertionError

有关更多信息和选项:https://pandas.pydata.org/docs/reference/testing.html


-1
投票

你也可以用

snapshottest
来做类似的事情。

https://stackoverflow.com/a/64070787/3384609

© www.soinside.com 2019 - 2024. All rights reserved.