test_api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import numpy as np
  2. import pytest
  3. from pandas.errors import (
  4. DataError,
  5. SpecificationError,
  6. )
  7. from pandas import (
  8. DataFrame,
  9. Index,
  10. MultiIndex,
  11. Period,
  12. Series,
  13. Timestamp,
  14. concat,
  15. date_range,
  16. timedelta_range,
  17. )
  18. import pandas._testing as tm
  19. def test_getitem(step):
  20. frame = DataFrame(np.random.randn(5, 5))
  21. r = frame.rolling(window=5, step=step)
  22. tm.assert_index_equal(r._selected_obj.columns, frame[::step].columns)
  23. r = frame.rolling(window=5, step=step)[1]
  24. assert r._selected_obj.name == frame[::step].columns[1]
  25. # technically this is allowed
  26. r = frame.rolling(window=5, step=step)[1, 3]
  27. tm.assert_index_equal(r._selected_obj.columns, frame[::step].columns[[1, 3]])
  28. r = frame.rolling(window=5, step=step)[[1, 3]]
  29. tm.assert_index_equal(r._selected_obj.columns, frame[::step].columns[[1, 3]])
  30. def test_select_bad_cols():
  31. df = DataFrame([[1, 2]], columns=["A", "B"])
  32. g = df.rolling(window=5)
  33. with pytest.raises(KeyError, match="Columns not found: 'C'"):
  34. g[["C"]]
  35. with pytest.raises(KeyError, match="^[^A]+$"):
  36. # A should not be referenced as a bad column...
  37. # will have to rethink regex if you change message!
  38. g[["A", "C"]]
  39. def test_attribute_access():
  40. df = DataFrame([[1, 2]], columns=["A", "B"])
  41. r = df.rolling(window=5)
  42. tm.assert_series_equal(r.A.sum(), r["A"].sum())
  43. msg = "'Rolling' object has no attribute 'F'"
  44. with pytest.raises(AttributeError, match=msg):
  45. r.F
  46. def tests_skip_nuisance(step):
  47. df = DataFrame({"A": range(5), "B": range(5, 10), "C": "foo"})
  48. r = df.rolling(window=3, step=step)
  49. result = r[["A", "B"]].sum()
  50. expected = DataFrame(
  51. {"A": [np.nan, np.nan, 3, 6, 9], "B": [np.nan, np.nan, 18, 21, 24]},
  52. columns=list("AB"),
  53. )[::step]
  54. tm.assert_frame_equal(result, expected)
  55. def test_sum_object_str_raises(step):
  56. df = DataFrame({"A": range(5), "B": range(5, 10), "C": "foo"})
  57. r = df.rolling(window=3, step=step)
  58. with pytest.raises(DataError, match="Cannot aggregate non-numeric type: object"):
  59. # GH#42738, enforced in 2.0
  60. r.sum()
  61. def test_agg(step):
  62. df = DataFrame({"A": range(5), "B": range(0, 10, 2)})
  63. r = df.rolling(window=3, step=step)
  64. a_mean = r["A"].mean()
  65. a_std = r["A"].std()
  66. a_sum = r["A"].sum()
  67. b_mean = r["B"].mean()
  68. b_std = r["B"].std()
  69. result = r.aggregate([np.mean, np.std])
  70. expected = concat([a_mean, a_std, b_mean, b_std], axis=1)
  71. expected.columns = MultiIndex.from_product([["A", "B"], ["mean", "std"]])
  72. tm.assert_frame_equal(result, expected)
  73. result = r.aggregate({"A": np.mean, "B": np.std})
  74. expected = concat([a_mean, b_std], axis=1)
  75. tm.assert_frame_equal(result, expected, check_like=True)
  76. result = r.aggregate({"A": ["mean", "std"]})
  77. expected = concat([a_mean, a_std], axis=1)
  78. expected.columns = MultiIndex.from_tuples([("A", "mean"), ("A", "std")])
  79. tm.assert_frame_equal(result, expected)
  80. result = r["A"].aggregate(["mean", "sum"])
  81. expected = concat([a_mean, a_sum], axis=1)
  82. expected.columns = ["mean", "sum"]
  83. tm.assert_frame_equal(result, expected)
  84. msg = "nested renamer is not supported"
  85. with pytest.raises(SpecificationError, match=msg):
  86. # using a dict with renaming
  87. r.aggregate({"A": {"mean": "mean", "sum": "sum"}})
  88. with pytest.raises(SpecificationError, match=msg):
  89. r.aggregate(
  90. {"A": {"mean": "mean", "sum": "sum"}, "B": {"mean2": "mean", "sum2": "sum"}}
  91. )
  92. result = r.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]})
  93. expected = concat([a_mean, a_std, b_mean, b_std], axis=1)
  94. exp_cols = [("A", "mean"), ("A", "std"), ("B", "mean"), ("B", "std")]
  95. expected.columns = MultiIndex.from_tuples(exp_cols)
  96. tm.assert_frame_equal(result, expected, check_like=True)
  97. @pytest.mark.parametrize(
  98. "func", [["min"], ["mean", "max"], {"b": "sum"}, {"b": "prod", "c": "median"}]
  99. )
  100. def test_multi_axis_1_raises(func):
  101. # GH#46904
  102. df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5], "c": [6, 7, 8]})
  103. r = df.rolling(window=3, axis=1)
  104. with pytest.raises(NotImplementedError, match="axis other than 0 is not supported"):
  105. r.agg(func)
  106. def test_agg_apply(raw):
  107. # passed lambda
  108. df = DataFrame({"A": range(5), "B": range(0, 10, 2)})
  109. r = df.rolling(window=3)
  110. a_sum = r["A"].sum()
  111. result = r.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)})
  112. rcustom = r["B"].apply(lambda x: np.std(x, ddof=1), raw=raw)
  113. expected = concat([a_sum, rcustom], axis=1)
  114. tm.assert_frame_equal(result, expected, check_like=True)
  115. def test_agg_consistency(step):
  116. df = DataFrame({"A": range(5), "B": range(0, 10, 2)})
  117. r = df.rolling(window=3, step=step)
  118. result = r.agg([np.sum, np.mean]).columns
  119. expected = MultiIndex.from_product([list("AB"), ["sum", "mean"]])
  120. tm.assert_index_equal(result, expected)
  121. result = r["A"].agg([np.sum, np.mean]).columns
  122. expected = Index(["sum", "mean"])
  123. tm.assert_index_equal(result, expected)
  124. result = r.agg({"A": [np.sum, np.mean]}).columns
  125. expected = MultiIndex.from_tuples([("A", "sum"), ("A", "mean")])
  126. tm.assert_index_equal(result, expected)
  127. def test_agg_nested_dicts():
  128. # API change for disallowing these types of nested dicts
  129. df = DataFrame({"A": range(5), "B": range(0, 10, 2)})
  130. r = df.rolling(window=3)
  131. msg = "nested renamer is not supported"
  132. with pytest.raises(SpecificationError, match=msg):
  133. r.aggregate({"r1": {"A": ["mean", "sum"]}, "r2": {"B": ["mean", "sum"]}})
  134. expected = concat(
  135. [r["A"].mean(), r["A"].std(), r["B"].mean(), r["B"].std()], axis=1
  136. )
  137. expected.columns = MultiIndex.from_tuples(
  138. [("ra", "mean"), ("ra", "std"), ("rb", "mean"), ("rb", "std")]
  139. )
  140. with pytest.raises(SpecificationError, match=msg):
  141. r[["A", "B"]].agg({"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}})
  142. with pytest.raises(SpecificationError, match=msg):
  143. r.agg({"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}})
  144. def test_count_nonnumeric_types(step):
  145. # GH12541
  146. cols = [
  147. "int",
  148. "float",
  149. "string",
  150. "datetime",
  151. "timedelta",
  152. "periods",
  153. "fl_inf",
  154. "fl_nan",
  155. "str_nan",
  156. "dt_nat",
  157. "periods_nat",
  158. ]
  159. dt_nat_col = [Timestamp("20170101"), Timestamp("20170203"), Timestamp(None)]
  160. df = DataFrame(
  161. {
  162. "int": [1, 2, 3],
  163. "float": [4.0, 5.0, 6.0],
  164. "string": list("abc"),
  165. "datetime": date_range("20170101", periods=3),
  166. "timedelta": timedelta_range("1 s", periods=3, freq="s"),
  167. "periods": [
  168. Period("2012-01"),
  169. Period("2012-02"),
  170. Period("2012-03"),
  171. ],
  172. "fl_inf": [1.0, 2.0, np.Inf],
  173. "fl_nan": [1.0, 2.0, np.NaN],
  174. "str_nan": ["aa", "bb", np.NaN],
  175. "dt_nat": dt_nat_col,
  176. "periods_nat": [
  177. Period("2012-01"),
  178. Period("2012-02"),
  179. Period(None),
  180. ],
  181. },
  182. columns=cols,
  183. )
  184. expected = DataFrame(
  185. {
  186. "int": [1.0, 2.0, 2.0],
  187. "float": [1.0, 2.0, 2.0],
  188. "string": [1.0, 2.0, 2.0],
  189. "datetime": [1.0, 2.0, 2.0],
  190. "timedelta": [1.0, 2.0, 2.0],
  191. "periods": [1.0, 2.0, 2.0],
  192. "fl_inf": [1.0, 2.0, 2.0],
  193. "fl_nan": [1.0, 2.0, 1.0],
  194. "str_nan": [1.0, 2.0, 1.0],
  195. "dt_nat": [1.0, 2.0, 1.0],
  196. "periods_nat": [1.0, 2.0, 1.0],
  197. },
  198. columns=cols,
  199. )[::step]
  200. result = df.rolling(window=2, min_periods=0, step=step).count()
  201. tm.assert_frame_equal(result, expected)
  202. result = df.rolling(1, min_periods=0, step=step).count()
  203. expected = df.notna().astype(float)[::step]
  204. tm.assert_frame_equal(result, expected)
  205. def test_preserve_metadata():
  206. # GH 10565
  207. s = Series(np.arange(100), name="foo")
  208. s2 = s.rolling(30).sum()
  209. s3 = s.rolling(20).sum()
  210. assert s2.name == "foo"
  211. assert s3.name == "foo"
  212. @pytest.mark.parametrize(
  213. "func,window_size,expected_vals",
  214. [
  215. (
  216. "rolling",
  217. 2,
  218. [
  219. [np.nan, np.nan, np.nan, np.nan],
  220. [15.0, 20.0, 25.0, 20.0],
  221. [25.0, 30.0, 35.0, 30.0],
  222. [np.nan, np.nan, np.nan, np.nan],
  223. [20.0, 30.0, 35.0, 30.0],
  224. [35.0, 40.0, 60.0, 40.0],
  225. [60.0, 80.0, 85.0, 80],
  226. ],
  227. ),
  228. (
  229. "expanding",
  230. None,
  231. [
  232. [10.0, 10.0, 20.0, 20.0],
  233. [15.0, 20.0, 25.0, 20.0],
  234. [20.0, 30.0, 30.0, 20.0],
  235. [10.0, 10.0, 30.0, 30.0],
  236. [20.0, 30.0, 35.0, 30.0],
  237. [26.666667, 40.0, 50.0, 30.0],
  238. [40.0, 80.0, 60.0, 30.0],
  239. ],
  240. ),
  241. ],
  242. )
  243. def test_multiple_agg_funcs(func, window_size, expected_vals):
  244. # GH 15072
  245. df = DataFrame(
  246. [
  247. ["A", 10, 20],
  248. ["A", 20, 30],
  249. ["A", 30, 40],
  250. ["B", 10, 30],
  251. ["B", 30, 40],
  252. ["B", 40, 80],
  253. ["B", 80, 90],
  254. ],
  255. columns=["stock", "low", "high"],
  256. )
  257. f = getattr(df.groupby("stock"), func)
  258. if window_size:
  259. window = f(window_size)
  260. else:
  261. window = f()
  262. index = MultiIndex.from_tuples(
  263. [("A", 0), ("A", 1), ("A", 2), ("B", 3), ("B", 4), ("B", 5), ("B", 6)],
  264. names=["stock", None],
  265. )
  266. columns = MultiIndex.from_tuples(
  267. [("low", "mean"), ("low", "max"), ("high", "mean"), ("high", "min")]
  268. )
  269. expected = DataFrame(expected_vals, index=index, columns=columns)
  270. result = window.agg({"low": ["mean", "max"], "high": ["mean", "min"]})
  271. tm.assert_frame_equal(result, expected)
  272. def test_dont_modify_attributes_after_methods(
  273. arithmetic_win_operators, closed, center, min_periods, step
  274. ):
  275. # GH 39554
  276. roll_obj = Series(range(1)).rolling(
  277. 1, center=center, closed=closed, min_periods=min_periods, step=step
  278. )
  279. expected = {attr: getattr(roll_obj, attr) for attr in roll_obj._attributes}
  280. getattr(roll_obj, arithmetic_win_operators)()
  281. result = {attr: getattr(roll_obj, attr) for attr in roll_obj._attributes}
  282. assert result == expected
  283. def test_centered_axis_validation(step):
  284. # ok
  285. Series(np.ones(10)).rolling(window=3, center=True, axis=0, step=step).mean()
  286. # bad axis
  287. msg = "No axis named 1 for object type Series"
  288. with pytest.raises(ValueError, match=msg):
  289. Series(np.ones(10)).rolling(window=3, center=True, axis=1, step=step).mean()
  290. # ok ok
  291. DataFrame(np.ones((10, 10))).rolling(
  292. window=3, center=True, axis=0, step=step
  293. ).mean()
  294. DataFrame(np.ones((10, 10))).rolling(
  295. window=3, center=True, axis=1, step=step
  296. ).mean()
  297. # bad axis
  298. msg = "No axis named 2 for object type DataFrame"
  299. with pytest.raises(ValueError, match=msg):
  300. (
  301. DataFrame(np.ones((10, 10)))
  302. .rolling(window=3, center=True, axis=2, step=step)
  303. .mean()
  304. )
  305. def test_rolling_min_min_periods(step):
  306. a = Series([1, 2, 3, 4, 5])
  307. result = a.rolling(window=100, min_periods=1, step=step).min()
  308. expected = Series(np.ones(len(a)))[::step]
  309. tm.assert_series_equal(result, expected)
  310. msg = "min_periods 5 must be <= window 3"
  311. with pytest.raises(ValueError, match=msg):
  312. Series([1, 2, 3]).rolling(window=3, min_periods=5, step=step).min()
  313. def test_rolling_max_min_periods(step):
  314. a = Series([1, 2, 3, 4, 5], dtype=np.float64)
  315. result = a.rolling(window=100, min_periods=1, step=step).max()
  316. expected = a[::step]
  317. tm.assert_almost_equal(result, expected)
  318. msg = "min_periods 5 must be <= window 3"
  319. with pytest.raises(ValueError, match=msg):
  320. Series([1, 2, 3]).rolling(window=3, min_periods=5, step=step).max()