test_api.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. """
  2. Tests of the groupby API, including internal consistency and with other pandas objects.
  3. Tests in this file should only check the existence, names, and arguments of groupby
  4. methods. It should not test the results of any groupby operation.
  5. """
  6. import inspect
  7. import pytest
  8. from pandas import (
  9. DataFrame,
  10. Series,
  11. )
  12. from pandas.core.groupby.base import (
  13. groupby_other_methods,
  14. reduction_kernels,
  15. transformation_kernels,
  16. )
  17. from pandas.core.groupby.generic import (
  18. DataFrameGroupBy,
  19. SeriesGroupBy,
  20. )
  21. def test_tab_completion(multiindex_dataframe_random_data):
  22. grp = multiindex_dataframe_random_data.groupby(level="second")
  23. results = {v for v in dir(grp) if not v.startswith("_")}
  24. expected = {
  25. "A",
  26. "B",
  27. "C",
  28. "agg",
  29. "aggregate",
  30. "apply",
  31. "boxplot",
  32. "filter",
  33. "first",
  34. "get_group",
  35. "groups",
  36. "hist",
  37. "indices",
  38. "last",
  39. "max",
  40. "mean",
  41. "median",
  42. "min",
  43. "ngroups",
  44. "nth",
  45. "ohlc",
  46. "plot",
  47. "prod",
  48. "size",
  49. "std",
  50. "sum",
  51. "transform",
  52. "var",
  53. "sem",
  54. "count",
  55. "nunique",
  56. "head",
  57. "describe",
  58. "cummax",
  59. "quantile",
  60. "rank",
  61. "cumprod",
  62. "tail",
  63. "resample",
  64. "cummin",
  65. "fillna",
  66. "cumsum",
  67. "cumcount",
  68. "ngroup",
  69. "all",
  70. "shift",
  71. "skew",
  72. "take",
  73. "pct_change",
  74. "any",
  75. "corr",
  76. "corrwith",
  77. "cov",
  78. "dtypes",
  79. "ndim",
  80. "diff",
  81. "idxmax",
  82. "idxmin",
  83. "ffill",
  84. "bfill",
  85. "rolling",
  86. "expanding",
  87. "pipe",
  88. "sample",
  89. "ewm",
  90. "value_counts",
  91. }
  92. assert results == expected
  93. def test_all_methods_categorized(multiindex_dataframe_random_data):
  94. grp = multiindex_dataframe_random_data.groupby(
  95. multiindex_dataframe_random_data.iloc[:, 0]
  96. )
  97. names = {_ for _ in dir(grp) if not _.startswith("_")} - set(
  98. multiindex_dataframe_random_data.columns
  99. )
  100. new_names = set(names)
  101. new_names -= reduction_kernels
  102. new_names -= transformation_kernels
  103. new_names -= groupby_other_methods
  104. assert not reduction_kernels & transformation_kernels
  105. assert not reduction_kernels & groupby_other_methods
  106. assert not transformation_kernels & groupby_other_methods
  107. # new public method?
  108. if new_names:
  109. msg = f"""
  110. There are uncategorized methods defined on the Grouper class:
  111. {new_names}.
  112. Was a new method recently added?
  113. Every public method On Grouper must appear in exactly one the
  114. following three lists defined in pandas.core.groupby.base:
  115. - `reduction_kernels`
  116. - `transformation_kernels`
  117. - `groupby_other_methods`
  118. see the comments in pandas/core/groupby/base.py for guidance on
  119. how to fix this test.
  120. """
  121. raise AssertionError(msg)
  122. # removed a public method?
  123. all_categorized = reduction_kernels | transformation_kernels | groupby_other_methods
  124. if names != all_categorized:
  125. msg = f"""
  126. Some methods which are supposed to be on the Grouper class
  127. are missing:
  128. {all_categorized - names}.
  129. They're still defined in one of the lists that live in pandas/core/groupby/base.py.
  130. If you removed a method, you should update them
  131. """
  132. raise AssertionError(msg)
  133. def test_frame_consistency(groupby_func):
  134. # GH#48028
  135. if groupby_func in ("first", "last"):
  136. msg = "first and last are entirely different between frame and groupby"
  137. pytest.skip(reason=msg)
  138. if groupby_func in ("cumcount", "ngroup"):
  139. assert not hasattr(DataFrame, groupby_func)
  140. return
  141. frame_method = getattr(DataFrame, groupby_func)
  142. gb_method = getattr(DataFrameGroupBy, groupby_func)
  143. result = set(inspect.signature(gb_method).parameters)
  144. if groupby_func == "size":
  145. # "size" is a method on GroupBy but property on DataFrame:
  146. expected = {"self"}
  147. else:
  148. expected = set(inspect.signature(frame_method).parameters)
  149. # Exclude certain arguments from result and expected depending on the operation
  150. # Some of these may be purposeful inconsistencies between the APIs
  151. exclude_expected, exclude_result = set(), set()
  152. if groupby_func in ("any", "all"):
  153. exclude_expected = {"kwargs", "bool_only", "axis"}
  154. elif groupby_func in ("count",):
  155. exclude_expected = {"numeric_only", "axis"}
  156. elif groupby_func in ("nunique",):
  157. exclude_expected = {"axis"}
  158. elif groupby_func in ("max", "min"):
  159. exclude_expected = {"axis", "kwargs", "skipna"}
  160. exclude_result = {"min_count", "engine", "engine_kwargs"}
  161. elif groupby_func in ("mean", "std", "sum", "var"):
  162. exclude_expected = {"axis", "kwargs", "skipna"}
  163. exclude_result = {"engine", "engine_kwargs"}
  164. elif groupby_func in ("median", "prod", "sem"):
  165. exclude_expected = {"axis", "kwargs", "skipna"}
  166. elif groupby_func in ("backfill", "bfill", "ffill", "pad"):
  167. exclude_expected = {"downcast", "inplace", "axis", "limit_area"}
  168. elif groupby_func in ("cummax", "cummin"):
  169. exclude_expected = {"skipna", "args"}
  170. exclude_result = {"numeric_only"}
  171. elif groupby_func in ("cumprod", "cumsum"):
  172. exclude_expected = {"skipna"}
  173. elif groupby_func in ("pct_change",):
  174. exclude_expected = {"kwargs"}
  175. exclude_result = {"axis"}
  176. elif groupby_func in ("rank",):
  177. exclude_expected = {"numeric_only"}
  178. elif groupby_func in ("quantile",):
  179. exclude_expected = {"method", "axis"}
  180. # Ensure excluded arguments are actually in the signatures
  181. assert result & exclude_result == exclude_result
  182. assert expected & exclude_expected == exclude_expected
  183. result -= exclude_result
  184. expected -= exclude_expected
  185. assert result == expected
  186. def test_series_consistency(request, groupby_func):
  187. # GH#48028
  188. if groupby_func in ("first", "last"):
  189. pytest.skip("first and last are entirely different between Series and groupby")
  190. if groupby_func in ("cumcount", "corrwith", "ngroup"):
  191. assert not hasattr(Series, groupby_func)
  192. return
  193. series_method = getattr(Series, groupby_func)
  194. gb_method = getattr(SeriesGroupBy, groupby_func)
  195. result = set(inspect.signature(gb_method).parameters)
  196. if groupby_func == "size":
  197. # "size" is a method on GroupBy but property on Series
  198. expected = {"self"}
  199. else:
  200. expected = set(inspect.signature(series_method).parameters)
  201. # Exclude certain arguments from result and expected depending on the operation
  202. # Some of these may be purposeful inconsistencies between the APIs
  203. exclude_expected, exclude_result = set(), set()
  204. if groupby_func in ("any", "all"):
  205. exclude_expected = {"kwargs", "bool_only", "axis"}
  206. elif groupby_func in ("diff",):
  207. exclude_result = {"axis"}
  208. elif groupby_func in ("max", "min"):
  209. exclude_expected = {"axis", "kwargs", "skipna"}
  210. exclude_result = {"min_count", "engine", "engine_kwargs"}
  211. elif groupby_func in ("mean", "std", "sum", "var"):
  212. exclude_expected = {"axis", "kwargs", "skipna"}
  213. exclude_result = {"engine", "engine_kwargs"}
  214. elif groupby_func in ("median", "prod", "sem"):
  215. exclude_expected = {"axis", "kwargs", "skipna"}
  216. elif groupby_func in ("backfill", "bfill", "ffill", "pad"):
  217. exclude_expected = {"downcast", "inplace", "axis", "limit_area"}
  218. elif groupby_func in ("cummax", "cummin"):
  219. exclude_expected = {"skipna", "args"}
  220. exclude_result = {"numeric_only"}
  221. elif groupby_func in ("cumprod", "cumsum"):
  222. exclude_expected = {"skipna"}
  223. elif groupby_func in ("pct_change",):
  224. exclude_expected = {"kwargs"}
  225. exclude_result = {"axis"}
  226. elif groupby_func in ("rank",):
  227. exclude_expected = {"numeric_only"}
  228. elif groupby_func in ("idxmin", "idxmax"):
  229. exclude_expected = {"args", "kwargs"}
  230. elif groupby_func in ("quantile",):
  231. exclude_result = {"numeric_only"}
  232. # Ensure excluded arguments are actually in the signatures
  233. assert result & exclude_result == exclude_result
  234. assert expected & exclude_expected == exclude_expected
  235. result -= exclude_result
  236. expected -= exclude_expected
  237. assert result == expected