test_util.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import numpy as np
  2. import pytest
  3. from pandas import Index, date_range
  4. from pandas.core.reshape.util import cartesian_product
  5. import pandas.util.testing as tm
  6. class TestCartesianProduct(object):
  7. def test_simple(self):
  8. x, y = list('ABC'), [1, 22]
  9. result1, result2 = cartesian_product([x, y])
  10. expected1 = np.array(['A', 'A', 'B', 'B', 'C', 'C'])
  11. expected2 = np.array([1, 22, 1, 22, 1, 22])
  12. tm.assert_numpy_array_equal(result1, expected1)
  13. tm.assert_numpy_array_equal(result2, expected2)
  14. def test_datetimeindex(self):
  15. # regression test for GitHub issue #6439
  16. # make sure that the ordering on datetimeindex is consistent
  17. x = date_range('2000-01-01', periods=2)
  18. result1, result2 = [Index(y).day for y in cartesian_product([x, x])]
  19. expected1 = Index([1, 1, 2, 2])
  20. expected2 = Index([1, 2, 1, 2])
  21. tm.assert_index_equal(result1, expected1)
  22. tm.assert_index_equal(result2, expected2)
  23. def test_empty(self):
  24. # product of empty factors
  25. X = [[], [0, 1], []]
  26. Y = [[], [], ['a', 'b', 'c']]
  27. for x, y in zip(X, Y):
  28. expected1 = np.array([], dtype=np.asarray(x).dtype)
  29. expected2 = np.array([], dtype=np.asarray(y).dtype)
  30. result1, result2 = cartesian_product([x, y])
  31. tm.assert_numpy_array_equal(result1, expected1)
  32. tm.assert_numpy_array_equal(result2, expected2)
  33. # empty product (empty input):
  34. result = cartesian_product([])
  35. expected = []
  36. assert result == expected
  37. @pytest.mark.parametrize("X", [
  38. 1, [1], [1, 2], [[1], 2],
  39. 'a', ['a'], ['a', 'b'], [['a'], 'b']
  40. ])
  41. def test_invalid_input(self, X):
  42. msg = "Input must be a list-like of list-likes"
  43. with pytest.raises(TypeError, match=msg):
  44. cartesian_product(X=X)