|
| 1 | +import unittest |
| 2 | +import numpy as np |
| 3 | +from Orange.data import ContinuousVariable, DiscreteVariable, TimeVariable |
| 4 | + |
| 5 | +try: |
| 6 | + import pandas as pd |
| 7 | +except ImportError: |
| 8 | + pd = None |
| 9 | + |
| 10 | +@unittest.skipIf(pd is None, "Missing package 'pandas'") |
| 11 | +class TestPandasCompat(unittest.TestCase): |
| 12 | + def test_table_from_frame(self): |
| 13 | + from Orange.data.pandas_compat import table_from_frame |
| 14 | + |
| 15 | + nan = np.nan |
| 16 | + df = pd.DataFrame([['a', 1, pd.Timestamp('2017-12-19')], |
| 17 | + ['b', 0, pd.Timestamp('1724-12-20')], |
| 18 | + ['c', 0, pd.Timestamp('1724-12-20')], |
| 19 | + [nan, nan, nan]]) |
| 20 | + table = table_from_frame(df) |
| 21 | + np.testing.assert_equal(table.X, |
| 22 | + [[1, pd.Timestamp('2017-12-19').timestamp()], |
| 23 | + [0, pd.Timestamp('1724-12-20').timestamp()], |
| 24 | + [0, pd.Timestamp('1724-12-20').timestamp()], |
| 25 | + [nan, nan]]) |
| 26 | + np.testing.assert_equal(table.metas.tolist(), [['a'], |
| 27 | + ['b'], |
| 28 | + ['c'], |
| 29 | + [nan]]) |
| 30 | + names = [var.name for var in table.domain.attributes] |
| 31 | + types = [type(var) for var in table.domain.attributes] |
| 32 | + self.assertEqual(names, ['1', '2']) |
| 33 | + self.assertEqual(types, [ContinuousVariable, TimeVariable]) |
| 34 | + |
| 35 | + # Force strings nominal |
| 36 | + table = table_from_frame(df, force_nominal=True) |
| 37 | + np.testing.assert_equal(table.X, [[0, 1, pd.Timestamp('2017-12-19').timestamp()], |
| 38 | + [1, 0, pd.Timestamp('1724-12-20').timestamp()], |
| 39 | + [2, 0, pd.Timestamp('1724-12-20').timestamp()], |
| 40 | + [nan, nan, nan]]) |
| 41 | + np.testing.assert_equal(table.metas.tolist(), [[], [], [], []]) |
| 42 | + names = [var.name for var in table.domain.attributes] |
| 43 | + types = [type(var) for var in table.domain.attributes] |
| 44 | + self.assertEqual(names, ['0', '1', '2']) |
| 45 | + self.assertEqual(types, [DiscreteVariable, ContinuousVariable, TimeVariable]) |
| 46 | + |
| 47 | + # Include index |
| 48 | + df.index = list('abaa') |
| 49 | + table = table_from_frame(df) |
| 50 | + np.testing.assert_equal(table.X, |
| 51 | + [[0, 1, pd.Timestamp('2017-12-19').timestamp()], |
| 52 | + [1, 0, pd.Timestamp('1724-12-20').timestamp()], |
| 53 | + [0, 0, pd.Timestamp('1724-12-20').timestamp()], |
| 54 | + [0, nan, nan]]) |
| 55 | + np.testing.assert_equal(table.metas.tolist(), [['a'], |
| 56 | + ['b'], |
| 57 | + ['c'], |
| 58 | + [nan]]) |
| 59 | + names = [var.name for var in table.domain.attributes] |
| 60 | + types = [type(var) for var in table.domain.attributes] |
| 61 | + self.assertEqual(names, ['index', '1', '2']) |
| 62 | + self.assertEqual(types, [DiscreteVariable, ContinuousVariable, TimeVariable]) |
0 commit comments