Home > Enterprise >  How to compare 2 dataframes in python unittest using assert methods
How to compare 2 dataframes in python unittest using assert methods

Time:10-12

I'm writing unittest for a method that returns a dataframe, but, while testing the output using:

self.asserEquals(mock_df, result)

I'm getting ValueError:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Right now I'm comparing properties that serves the purpose now,

self.assertEqual(mock_df.size, result.size)
self.assertEqual(mock_df.col_a.to_list(), result.col_a.to_list())
self.assertEqual(mock_df.col_b.to_list(), result.col_b.to_list())
self.assertEqual(mock_df.col_c.to_list(), result.col_c.to_list())

but curious how do I assert dataframes.

CodePudding user response:

import unittest
import pandas as pd

class TestDataFrame(unittest.TestCase):
    def test_dataframe(self):
        df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
        df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]})
        self.assertEqual(True, df1.equals(df2))

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