test_subclass.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import numpy as np
  2. import pytest
  3. import pandas as pd
  4. import pandas._testing as tm
  5. pytestmark = pytest.mark.filterwarnings(
  6. "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"
  7. )
  8. class TestSeriesSubclassing:
  9. @pytest.mark.parametrize(
  10. "idx_method, indexer, exp_data, exp_idx",
  11. [
  12. ["loc", ["a", "b"], [1, 2], "ab"],
  13. ["iloc", [2, 3], [3, 4], "cd"],
  14. ],
  15. )
  16. def test_indexing_sliced(self, idx_method, indexer, exp_data, exp_idx):
  17. s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"))
  18. res = getattr(s, idx_method)[indexer]
  19. exp = tm.SubclassedSeries(exp_data, index=list(exp_idx))
  20. tm.assert_series_equal(res, exp)
  21. def test_to_frame(self):
  22. s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"), name="xxx")
  23. res = s.to_frame()
  24. exp = tm.SubclassedDataFrame({"xxx": [1, 2, 3, 4]}, index=list("abcd"))
  25. tm.assert_frame_equal(res, exp)
  26. def test_subclass_unstack(self):
  27. # GH 15564
  28. s = tm.SubclassedSeries([1, 2, 3, 4], index=[list("aabb"), list("xyxy")])
  29. res = s.unstack()
  30. exp = tm.SubclassedDataFrame({"x": [1, 3], "y": [2, 4]}, index=["a", "b"])
  31. tm.assert_frame_equal(res, exp)
  32. def test_subclass_empty_repr(self):
  33. sub_series = tm.SubclassedSeries()
  34. assert "SubclassedSeries" in repr(sub_series)
  35. def test_asof(self):
  36. N = 3
  37. rng = pd.date_range("1/1/1990", periods=N, freq="53s")
  38. s = tm.SubclassedSeries({"A": [np.nan, np.nan, np.nan]}, index=rng)
  39. result = s.asof(rng[-2:])
  40. assert isinstance(result, tm.SubclassedSeries)
  41. def test_explode(self):
  42. s = tm.SubclassedSeries([[1, 2, 3], "foo", [], [3, 4]])
  43. result = s.explode()
  44. assert isinstance(result, tm.SubclassedSeries)
  45. def test_equals(self):
  46. # https://github.com/pandas-dev/pandas/pull/34402
  47. # allow subclass in both directions
  48. s1 = pd.Series([1, 2, 3])
  49. s2 = tm.SubclassedSeries([1, 2, 3])
  50. assert s1.equals(s2)
  51. assert s2.equals(s1)
  52. class SubclassedSeries(pd.Series):
  53. @property
  54. def _constructor(self):
  55. def _new(*args, **kwargs):
  56. # some constructor logic that accesses the Series' name
  57. if self.name == "test":
  58. return pd.Series(*args, **kwargs)
  59. return SubclassedSeries(*args, **kwargs)
  60. return _new
  61. def test_constructor_from_dict():
  62. # https://github.com/pandas-dev/pandas/issues/52445
  63. result = SubclassedSeries({"a": 1, "b": 2, "c": 3})
  64. assert isinstance(result, SubclassedSeries)