test_cumulative.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """
  2. Tests for DataFrame cumulative operations
  3. See also
  4. --------
  5. tests.series.test_cumulative
  6. """
  7. import numpy as np
  8. import pytest
  9. from pandas import (
  10. DataFrame,
  11. Series,
  12. )
  13. import pandas._testing as tm
  14. class TestDataFrameCumulativeOps:
  15. # ---------------------------------------------------------------------
  16. # Cumulative Operations - cumsum, cummax, ...
  17. def test_cumulative_ops_smoke(self):
  18. # it works
  19. df = DataFrame({"A": np.arange(20)}, index=np.arange(20))
  20. df.cummax()
  21. df.cummin()
  22. df.cumsum()
  23. dm = DataFrame(np.arange(20).reshape(4, 5), index=range(4), columns=range(5))
  24. # TODO(wesm): do something with this?
  25. dm.cumsum()
  26. def test_cumprod_smoke(self, datetime_frame):
  27. datetime_frame.iloc[5:10, 0] = np.nan
  28. datetime_frame.iloc[10:15, 1] = np.nan
  29. datetime_frame.iloc[15:, 2] = np.nan
  30. # ints
  31. df = datetime_frame.fillna(0).astype(int)
  32. df.cumprod(0)
  33. df.cumprod(1)
  34. # ints32
  35. df = datetime_frame.fillna(0).astype(np.int32)
  36. df.cumprod(0)
  37. df.cumprod(1)
  38. @pytest.mark.parametrize("method", ["cumsum", "cumprod", "cummin", "cummax"])
  39. def test_cumulative_ops_match_series_apply(self, datetime_frame, method):
  40. datetime_frame.iloc[5:10, 0] = np.nan
  41. datetime_frame.iloc[10:15, 1] = np.nan
  42. datetime_frame.iloc[15:, 2] = np.nan
  43. # axis = 0
  44. result = getattr(datetime_frame, method)()
  45. expected = datetime_frame.apply(getattr(Series, method))
  46. tm.assert_frame_equal(result, expected)
  47. # axis = 1
  48. result = getattr(datetime_frame, method)(axis=1)
  49. expected = datetime_frame.apply(getattr(Series, method), axis=1)
  50. tm.assert_frame_equal(result, expected)
  51. # fix issue TODO: GH ref?
  52. assert np.shape(result) == np.shape(datetime_frame)
  53. def test_cumsum_preserve_dtypes(self):
  54. # GH#19296 dont incorrectly upcast to object
  55. df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3.0], "C": [True, False, False]})
  56. result = df.cumsum()
  57. expected = DataFrame(
  58. {
  59. "A": Series([1, 3, 6], dtype=np.int64),
  60. "B": Series([1, 3, 6], dtype=np.float64),
  61. "C": df["C"].cumsum(),
  62. }
  63. )
  64. tm.assert_frame_equal(result, expected)