test_rank.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. from datetime import (
  2. datetime,
  3. timedelta,
  4. )
  5. import numpy as np
  6. import pytest
  7. from pandas._libs.algos import (
  8. Infinity,
  9. NegInfinity,
  10. )
  11. import pandas.util._test_decorators as td
  12. from pandas import (
  13. DataFrame,
  14. Series,
  15. )
  16. import pandas._testing as tm
  17. class TestRank:
  18. s = Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3])
  19. df = DataFrame({"A": s, "B": s})
  20. results = {
  21. "average": np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5]),
  22. "min": np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5]),
  23. "max": np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6]),
  24. "first": np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6]),
  25. "dense": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]),
  26. }
  27. @pytest.fixture(params=["average", "min", "max", "first", "dense"])
  28. def method(self, request):
  29. """
  30. Fixture for trying all rank methods
  31. """
  32. return request.param
  33. @td.skip_if_no_scipy
  34. def test_rank(self, float_frame):
  35. import scipy.stats # noqa:F401
  36. from scipy.stats import rankdata
  37. float_frame.loc[::2, "A"] = np.nan
  38. float_frame.loc[::3, "B"] = np.nan
  39. float_frame.loc[::4, "C"] = np.nan
  40. float_frame.loc[::5, "D"] = np.nan
  41. ranks0 = float_frame.rank()
  42. ranks1 = float_frame.rank(1)
  43. mask = np.isnan(float_frame.values)
  44. fvals = float_frame.fillna(np.inf).values
  45. exp0 = np.apply_along_axis(rankdata, 0, fvals)
  46. exp0[mask] = np.nan
  47. exp1 = np.apply_along_axis(rankdata, 1, fvals)
  48. exp1[mask] = np.nan
  49. tm.assert_almost_equal(ranks0.values, exp0)
  50. tm.assert_almost_equal(ranks1.values, exp1)
  51. # integers
  52. df = DataFrame(np.random.randint(0, 5, size=40).reshape((10, 4)))
  53. result = df.rank()
  54. exp = df.astype(float).rank()
  55. tm.assert_frame_equal(result, exp)
  56. result = df.rank(1)
  57. exp = df.astype(float).rank(1)
  58. tm.assert_frame_equal(result, exp)
  59. def test_rank2(self):
  60. df = DataFrame([[1, 3, 2], [1, 2, 3]])
  61. expected = DataFrame([[1.0, 3.0, 2.0], [1, 2, 3]]) / 3.0
  62. result = df.rank(1, pct=True)
  63. tm.assert_frame_equal(result, expected)
  64. df = DataFrame([[1, 3, 2], [1, 2, 3]])
  65. expected = df.rank(0) / 2.0
  66. result = df.rank(0, pct=True)
  67. tm.assert_frame_equal(result, expected)
  68. df = DataFrame([["b", "c", "a"], ["a", "c", "b"]])
  69. expected = DataFrame([[2.0, 3.0, 1.0], [1, 3, 2]])
  70. result = df.rank(1, numeric_only=False)
  71. tm.assert_frame_equal(result, expected)
  72. expected = DataFrame([[2.0, 1.5, 1.0], [1, 1.5, 2]])
  73. result = df.rank(0, numeric_only=False)
  74. tm.assert_frame_equal(result, expected)
  75. df = DataFrame([["b", np.nan, "a"], ["a", "c", "b"]])
  76. expected = DataFrame([[2.0, np.nan, 1.0], [1.0, 3.0, 2.0]])
  77. result = df.rank(1, numeric_only=False)
  78. tm.assert_frame_equal(result, expected)
  79. expected = DataFrame([[2.0, np.nan, 1.0], [1.0, 1.0, 2.0]])
  80. result = df.rank(0, numeric_only=False)
  81. tm.assert_frame_equal(result, expected)
  82. # f7u12, this does not work without extensive workaround
  83. data = [
  84. [datetime(2001, 1, 5), np.nan, datetime(2001, 1, 2)],
  85. [datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 1)],
  86. ]
  87. df = DataFrame(data)
  88. # check the rank
  89. expected = DataFrame([[2.0, np.nan, 1.0], [2.0, 3.0, 1.0]])
  90. result = df.rank(1, numeric_only=False, ascending=True)
  91. tm.assert_frame_equal(result, expected)
  92. expected = DataFrame([[1.0, np.nan, 2.0], [2.0, 1.0, 3.0]])
  93. result = df.rank(1, numeric_only=False, ascending=False)
  94. tm.assert_frame_equal(result, expected)
  95. df = DataFrame({"a": [1e-20, -5, 1e-20 + 1e-40, 10, 1e60, 1e80, 1e-30]})
  96. exp = DataFrame({"a": [3.5, 1.0, 3.5, 5.0, 6.0, 7.0, 2.0]})
  97. tm.assert_frame_equal(df.rank(), exp)
  98. def test_rank_does_not_mutate(self):
  99. # GH#18521
  100. # Check rank does not mutate DataFrame
  101. df = DataFrame(np.random.randn(10, 3), dtype="float64")
  102. expected = df.copy()
  103. df.rank()
  104. result = df
  105. tm.assert_frame_equal(result, expected)
  106. def test_rank_mixed_frame(self, float_string_frame):
  107. float_string_frame["datetime"] = datetime.now()
  108. float_string_frame["timedelta"] = timedelta(days=1, seconds=1)
  109. float_string_frame.rank(numeric_only=False)
  110. with pytest.raises(TypeError, match="not supported between instances of"):
  111. float_string_frame.rank(axis=1)
  112. @td.skip_if_no_scipy
  113. def test_rank_na_option(self, float_frame):
  114. import scipy.stats # noqa:F401
  115. from scipy.stats import rankdata
  116. float_frame.loc[::2, "A"] = np.nan
  117. float_frame.loc[::3, "B"] = np.nan
  118. float_frame.loc[::4, "C"] = np.nan
  119. float_frame.loc[::5, "D"] = np.nan
  120. # bottom
  121. ranks0 = float_frame.rank(na_option="bottom")
  122. ranks1 = float_frame.rank(1, na_option="bottom")
  123. fvals = float_frame.fillna(np.inf).values
  124. exp0 = np.apply_along_axis(rankdata, 0, fvals)
  125. exp1 = np.apply_along_axis(rankdata, 1, fvals)
  126. tm.assert_almost_equal(ranks0.values, exp0)
  127. tm.assert_almost_equal(ranks1.values, exp1)
  128. # top
  129. ranks0 = float_frame.rank(na_option="top")
  130. ranks1 = float_frame.rank(1, na_option="top")
  131. fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values
  132. fval1 = float_frame.T
  133. fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T
  134. fval1 = fval1.fillna(np.inf).values
  135. exp0 = np.apply_along_axis(rankdata, 0, fval0)
  136. exp1 = np.apply_along_axis(rankdata, 1, fval1)
  137. tm.assert_almost_equal(ranks0.values, exp0)
  138. tm.assert_almost_equal(ranks1.values, exp1)
  139. # descending
  140. # bottom
  141. ranks0 = float_frame.rank(na_option="top", ascending=False)
  142. ranks1 = float_frame.rank(1, na_option="top", ascending=False)
  143. fvals = float_frame.fillna(np.inf).values
  144. exp0 = np.apply_along_axis(rankdata, 0, -fvals)
  145. exp1 = np.apply_along_axis(rankdata, 1, -fvals)
  146. tm.assert_almost_equal(ranks0.values, exp0)
  147. tm.assert_almost_equal(ranks1.values, exp1)
  148. # descending
  149. # top
  150. ranks0 = float_frame.rank(na_option="bottom", ascending=False)
  151. ranks1 = float_frame.rank(1, na_option="bottom", ascending=False)
  152. fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values
  153. fval1 = float_frame.T
  154. fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T
  155. fval1 = fval1.fillna(np.inf).values
  156. exp0 = np.apply_along_axis(rankdata, 0, -fval0)
  157. exp1 = np.apply_along_axis(rankdata, 1, -fval1)
  158. tm.assert_numpy_array_equal(ranks0.values, exp0)
  159. tm.assert_numpy_array_equal(ranks1.values, exp1)
  160. # bad values throw error
  161. msg = "na_option must be one of 'keep', 'top', or 'bottom'"
  162. with pytest.raises(ValueError, match=msg):
  163. float_frame.rank(na_option="bad", ascending=False)
  164. # invalid type
  165. with pytest.raises(ValueError, match=msg):
  166. float_frame.rank(na_option=True, ascending=False)
  167. def test_rank_axis(self):
  168. # check if using axes' names gives the same result
  169. df = DataFrame([[2, 1], [4, 3]])
  170. tm.assert_frame_equal(df.rank(axis=0), df.rank(axis="index"))
  171. tm.assert_frame_equal(df.rank(axis=1), df.rank(axis="columns"))
  172. @td.skip_if_no_scipy
  173. def test_rank_methods_frame(self):
  174. import scipy.stats # noqa:F401
  175. from scipy.stats import rankdata
  176. xs = np.random.randint(0, 21, (100, 26))
  177. xs = (xs - 10.0) / 10.0
  178. cols = [chr(ord("z") - i) for i in range(xs.shape[1])]
  179. for vals in [xs, xs + 1e6, xs * 1e-6]:
  180. df = DataFrame(vals, columns=cols)
  181. for ax in [0, 1]:
  182. for m in ["average", "min", "max", "first", "dense"]:
  183. result = df.rank(axis=ax, method=m)
  184. sprank = np.apply_along_axis(
  185. rankdata, ax, vals, m if m != "first" else "ordinal"
  186. )
  187. sprank = sprank.astype(np.float64)
  188. expected = DataFrame(sprank, columns=cols).astype("float64")
  189. tm.assert_frame_equal(result, expected)
  190. @pytest.mark.parametrize("dtype", ["O", "f8", "i8"])
  191. def test_rank_descending(self, method, dtype):
  192. if "i" in dtype:
  193. df = self.df.dropna().astype(dtype)
  194. else:
  195. df = self.df.astype(dtype)
  196. res = df.rank(ascending=False)
  197. expected = (df.max() - df).rank()
  198. tm.assert_frame_equal(res, expected)
  199. expected = (df.max() - df).rank(method=method)
  200. if dtype != "O":
  201. res2 = df.rank(method=method, ascending=False, numeric_only=True)
  202. tm.assert_frame_equal(res2, expected)
  203. res3 = df.rank(method=method, ascending=False, numeric_only=False)
  204. tm.assert_frame_equal(res3, expected)
  205. @pytest.mark.parametrize("axis", [0, 1])
  206. @pytest.mark.parametrize("dtype", [None, object])
  207. def test_rank_2d_tie_methods(self, method, axis, dtype):
  208. df = self.df
  209. def _check2d(df, expected, method="average", axis=0):
  210. exp_df = DataFrame({"A": expected, "B": expected})
  211. if axis == 1:
  212. df = df.T
  213. exp_df = exp_df.T
  214. result = df.rank(method=method, axis=axis)
  215. tm.assert_frame_equal(result, exp_df)
  216. frame = df if dtype is None else df.astype(dtype)
  217. _check2d(frame, self.results[method], method=method, axis=axis)
  218. @pytest.mark.parametrize(
  219. "method,exp",
  220. [
  221. ("dense", [[1.0, 1.0, 1.0], [1.0, 0.5, 2.0 / 3], [1.0, 0.5, 1.0 / 3]]),
  222. (
  223. "min",
  224. [
  225. [1.0 / 3, 1.0, 1.0],
  226. [1.0 / 3, 1.0 / 3, 2.0 / 3],
  227. [1.0 / 3, 1.0 / 3, 1.0 / 3],
  228. ],
  229. ),
  230. (
  231. "max",
  232. [[1.0, 1.0, 1.0], [1.0, 2.0 / 3, 2.0 / 3], [1.0, 2.0 / 3, 1.0 / 3]],
  233. ),
  234. (
  235. "average",
  236. [[2.0 / 3, 1.0, 1.0], [2.0 / 3, 0.5, 2.0 / 3], [2.0 / 3, 0.5, 1.0 / 3]],
  237. ),
  238. (
  239. "first",
  240. [
  241. [1.0 / 3, 1.0, 1.0],
  242. [2.0 / 3, 1.0 / 3, 2.0 / 3],
  243. [3.0 / 3, 2.0 / 3, 1.0 / 3],
  244. ],
  245. ),
  246. ],
  247. )
  248. def test_rank_pct_true(self, method, exp):
  249. # see gh-15630.
  250. df = DataFrame([[2012, 66, 3], [2012, 65, 2], [2012, 65, 1]])
  251. result = df.rank(method=method, pct=True)
  252. expected = DataFrame(exp)
  253. tm.assert_frame_equal(result, expected)
  254. @pytest.mark.single_cpu
  255. def test_pct_max_many_rows(self):
  256. # GH 18271
  257. df = DataFrame(
  258. {"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)}
  259. )
  260. result = df.rank(pct=True).max()
  261. assert (result == 1).all()
  262. @pytest.mark.parametrize(
  263. "contents,dtype",
  264. [
  265. (
  266. [
  267. -np.inf,
  268. -50,
  269. -1,
  270. -1e-20,
  271. -1e-25,
  272. -1e-50,
  273. 0,
  274. 1e-40,
  275. 1e-20,
  276. 1e-10,
  277. 2,
  278. 40,
  279. np.inf,
  280. ],
  281. "float64",
  282. ),
  283. (
  284. [
  285. -np.inf,
  286. -50,
  287. -1,
  288. -1e-20,
  289. -1e-25,
  290. -1e-45,
  291. 0,
  292. 1e-40,
  293. 1e-20,
  294. 1e-10,
  295. 2,
  296. 40,
  297. np.inf,
  298. ],
  299. "float32",
  300. ),
  301. ([np.iinfo(np.uint8).min, 1, 2, 100, np.iinfo(np.uint8).max], "uint8"),
  302. (
  303. [
  304. np.iinfo(np.int64).min,
  305. -100,
  306. 0,
  307. 1,
  308. 9999,
  309. 100000,
  310. 1e10,
  311. np.iinfo(np.int64).max,
  312. ],
  313. "int64",
  314. ),
  315. ([NegInfinity(), "1", "A", "BA", "Ba", "C", Infinity()], "object"),
  316. (
  317. [datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 5)],
  318. "datetime64",
  319. ),
  320. ],
  321. )
  322. def test_rank_inf_and_nan(self, contents, dtype, frame_or_series):
  323. dtype_na_map = {
  324. "float64": np.nan,
  325. "float32": np.nan,
  326. "object": None,
  327. "datetime64": np.datetime64("nat"),
  328. }
  329. # Insert nans at random positions if underlying dtype has missing
  330. # value. Then adjust the expected order by adding nans accordingly
  331. # This is for testing whether rank calculation is affected
  332. # when values are interwined with nan values.
  333. values = np.array(contents, dtype=dtype)
  334. exp_order = np.array(range(len(values)), dtype="float64") + 1.0
  335. if dtype in dtype_na_map:
  336. na_value = dtype_na_map[dtype]
  337. nan_indices = np.random.choice(range(len(values)), 5)
  338. values = np.insert(values, nan_indices, na_value)
  339. exp_order = np.insert(exp_order, nan_indices, np.nan)
  340. # Shuffle the testing array and expected results in the same way
  341. random_order = np.random.permutation(len(values))
  342. obj = frame_or_series(values[random_order])
  343. expected = frame_or_series(exp_order[random_order], dtype="float64")
  344. result = obj.rank()
  345. tm.assert_equal(result, expected)
  346. def test_df_series_inf_nan_consistency(self):
  347. # GH#32593
  348. index = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10]
  349. col1 = [5, 4, 3, 5, 8, 5, 2, 1, 6, 6]
  350. col2 = [5, 4, np.nan, 5, 8, 5, np.inf, np.nan, 6, -np.inf]
  351. df = DataFrame(
  352. data={
  353. "col1": col1,
  354. "col2": col2,
  355. },
  356. index=index,
  357. dtype="f8",
  358. )
  359. df_result = df.rank()
  360. series_result = df.copy()
  361. series_result["col1"] = df["col1"].rank()
  362. series_result["col2"] = df["col2"].rank()
  363. tm.assert_frame_equal(df_result, series_result)
  364. def test_rank_both_inf(self):
  365. # GH#32593
  366. df = DataFrame({"a": [-np.inf, 0, np.inf]})
  367. expected = DataFrame({"a": [1.0, 2.0, 3.0]})
  368. result = df.rank()
  369. tm.assert_frame_equal(result, expected)
  370. @pytest.mark.parametrize(
  371. "na_option,ascending,expected",
  372. [
  373. ("top", True, [3.0, 1.0, 2.0]),
  374. ("top", False, [2.0, 1.0, 3.0]),
  375. ("bottom", True, [2.0, 3.0, 1.0]),
  376. ("bottom", False, [1.0, 3.0, 2.0]),
  377. ],
  378. )
  379. def test_rank_inf_nans_na_option(
  380. self, frame_or_series, method, na_option, ascending, expected
  381. ):
  382. obj = frame_or_series([np.inf, np.nan, -np.inf])
  383. result = obj.rank(method=method, na_option=na_option, ascending=ascending)
  384. expected = frame_or_series(expected)
  385. tm.assert_equal(result, expected)
  386. @pytest.mark.parametrize(
  387. "na_option,ascending,expected",
  388. [
  389. ("bottom", True, [1.0, 2.0, 4.0, 3.0]),
  390. ("bottom", False, [1.0, 2.0, 4.0, 3.0]),
  391. ("top", True, [2.0, 3.0, 1.0, 4.0]),
  392. ("top", False, [2.0, 3.0, 1.0, 4.0]),
  393. ],
  394. )
  395. def test_rank_object_first(self, frame_or_series, na_option, ascending, expected):
  396. obj = frame_or_series(["foo", "foo", None, "foo"])
  397. result = obj.rank(method="first", na_option=na_option, ascending=ascending)
  398. expected = frame_or_series(expected)
  399. tm.assert_equal(result, expected)
  400. @pytest.mark.parametrize(
  401. "data,expected",
  402. [
  403. ({"a": [1, 2, "a"], "b": [4, 5, 6]}, DataFrame({"b": [1.0, 2.0, 3.0]})),
  404. ({"a": [1, 2, "a"]}, DataFrame(index=range(3), columns=[])),
  405. ],
  406. )
  407. def test_rank_mixed_axis_zero(self, data, expected):
  408. df = DataFrame(data)
  409. with pytest.raises(TypeError, match="'<' not supported between instances of"):
  410. df.rank()
  411. result = df.rank(numeric_only=True)
  412. tm.assert_frame_equal(result, expected)