如何在单元tes中使用pandas数据帧

2024-04-27 03:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我似乎无法让它加载数据帧并使用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()

谢谢你的帮助。


Tags: csv数据nametestself脚本inputdata
2条回答

如果你用的是最新的熊猫,我想下面的方法比较干净一些:

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/pandas-docs/stable/reference/general_utility_functions.html#testing-functions

熊猫有一些测试工具。

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)

相关问题 更多 >