test_sparse.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. """
  2. This file contains a minimal set of tests for compliance with the extension
  3. array interface test suite, and should contain no other tests.
  4. The test suite for the full functionality of the array is located in
  5. `pandas/tests/arrays/`.
  6. The tests in this file are inherited from the BaseExtensionTests, and only
  7. minimal tweaks should be applied to get the tests passing (by overwriting a
  8. parent method).
  9. Additional tests should either be added to one of the BaseExtensionTests
  10. classes (if they are relevant for the extension interface for all dtypes), or
  11. be added to the array-specific tests in `pandas/tests/arrays/`.
  12. """
  13. import numpy as np
  14. import pytest
  15. from pandas.errors import PerformanceWarning
  16. import pandas as pd
  17. from pandas import SparseDtype
  18. import pandas._testing as tm
  19. from pandas.arrays import SparseArray
  20. from pandas.tests.extension import base
  21. def make_data(fill_value):
  22. rng = np.random.default_rng(2)
  23. if np.isnan(fill_value):
  24. data = rng.uniform(size=100)
  25. else:
  26. data = rng.integers(1, 100, size=100, dtype=int)
  27. if data[0] == data[1]:
  28. data[0] += 1
  29. data[2::3] = fill_value
  30. return data
  31. @pytest.fixture
  32. def dtype():
  33. return SparseDtype()
  34. @pytest.fixture(params=[0, np.nan])
  35. def data(request):
  36. """Length-100 PeriodArray for semantics test."""
  37. res = SparseArray(make_data(request.param), fill_value=request.param)
  38. return res
  39. @pytest.fixture
  40. def data_for_twos():
  41. return SparseArray(np.ones(100) * 2)
  42. @pytest.fixture(params=[0, np.nan])
  43. def data_missing(request):
  44. """Length 2 array with [NA, Valid]"""
  45. return SparseArray([np.nan, 1], fill_value=request.param)
  46. @pytest.fixture(params=[0, np.nan])
  47. def data_repeated(request):
  48. """Return different versions of data for count times"""
  49. def gen(count):
  50. for _ in range(count):
  51. yield SparseArray(make_data(request.param), fill_value=request.param)
  52. yield gen
  53. @pytest.fixture(params=[0, np.nan])
  54. def data_for_sorting(request):
  55. return SparseArray([2, 3, 1], fill_value=request.param)
  56. @pytest.fixture(params=[0, np.nan])
  57. def data_missing_for_sorting(request):
  58. return SparseArray([2, np.nan, 1], fill_value=request.param)
  59. @pytest.fixture
  60. def na_cmp():
  61. return lambda left, right: pd.isna(left) and pd.isna(right)
  62. @pytest.fixture(params=[0, np.nan])
  63. def data_for_grouping(request):
  64. return SparseArray([1, 1, np.nan, np.nan, 2, 2, 1, 3], fill_value=request.param)
  65. @pytest.fixture(params=[0, np.nan])
  66. def data_for_compare(request):
  67. return SparseArray([0, 0, np.nan, -2, -1, 4, 2, 3, 0, 0], fill_value=request.param)
  68. class TestSparseArray(base.ExtensionTests):
  69. def _supports_reduction(self, obj, op_name: str) -> bool:
  70. return True
  71. @pytest.mark.parametrize("skipna", [True, False])
  72. def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request):
  73. if all_numeric_reductions in [
  74. "prod",
  75. "median",
  76. "var",
  77. "std",
  78. "sem",
  79. "skew",
  80. "kurt",
  81. ]:
  82. mark = pytest.mark.xfail(
  83. reason="This should be viable but is not implemented"
  84. )
  85. request.node.add_marker(mark)
  86. elif (
  87. all_numeric_reductions in ["sum", "max", "min", "mean"]
  88. and data.dtype.kind == "f"
  89. and not skipna
  90. ):
  91. mark = pytest.mark.xfail(reason="getting a non-nan float")
  92. request.node.add_marker(mark)
  93. super().test_reduce_series_numeric(data, all_numeric_reductions, skipna)
  94. @pytest.mark.parametrize("skipna", [True, False])
  95. def test_reduce_frame(self, data, all_numeric_reductions, skipna, request):
  96. if all_numeric_reductions in [
  97. "prod",
  98. "median",
  99. "var",
  100. "std",
  101. "sem",
  102. "skew",
  103. "kurt",
  104. ]:
  105. mark = pytest.mark.xfail(
  106. reason="This should be viable but is not implemented"
  107. )
  108. request.node.add_marker(mark)
  109. elif (
  110. all_numeric_reductions in ["sum", "max", "min", "mean"]
  111. and data.dtype.kind == "f"
  112. and not skipna
  113. ):
  114. mark = pytest.mark.xfail(reason="ExtensionArray NA mask are different")
  115. request.node.add_marker(mark)
  116. super().test_reduce_frame(data, all_numeric_reductions, skipna)
  117. def _check_unsupported(self, data):
  118. if data.dtype == SparseDtype(int, 0):
  119. pytest.skip("Can't store nan in int array.")
  120. def test_concat_mixed_dtypes(self, data):
  121. # https://github.com/pandas-dev/pandas/issues/20762
  122. # This should be the same, aside from concat([sparse, float])
  123. df1 = pd.DataFrame({"A": data[:3]})
  124. df2 = pd.DataFrame({"A": [1, 2, 3]})
  125. df3 = pd.DataFrame({"A": ["a", "b", "c"]}).astype("category")
  126. dfs = [df1, df2, df3]
  127. # dataframes
  128. result = pd.concat(dfs)
  129. expected = pd.concat(
  130. [x.apply(lambda s: np.asarray(s).astype(object)) for x in dfs]
  131. )
  132. tm.assert_frame_equal(result, expected)
  133. @pytest.mark.filterwarnings(
  134. "ignore:The previous implementation of stack is deprecated"
  135. )
  136. @pytest.mark.parametrize(
  137. "columns",
  138. [
  139. ["A", "B"],
  140. pd.MultiIndex.from_tuples(
  141. [("A", "a"), ("A", "b")], names=["outer", "inner"]
  142. ),
  143. ],
  144. )
  145. @pytest.mark.parametrize("future_stack", [True, False])
  146. def test_stack(self, data, columns, future_stack):
  147. super().test_stack(data, columns, future_stack)
  148. def test_concat_columns(self, data, na_value):
  149. self._check_unsupported(data)
  150. super().test_concat_columns(data, na_value)
  151. def test_concat_extension_arrays_copy_false(self, data, na_value):
  152. self._check_unsupported(data)
  153. super().test_concat_extension_arrays_copy_false(data, na_value)
  154. def test_align(self, data, na_value):
  155. self._check_unsupported(data)
  156. super().test_align(data, na_value)
  157. def test_align_frame(self, data, na_value):
  158. self._check_unsupported(data)
  159. super().test_align_frame(data, na_value)
  160. def test_align_series_frame(self, data, na_value):
  161. self._check_unsupported(data)
  162. super().test_align_series_frame(data, na_value)
  163. def test_merge(self, data, na_value):
  164. self._check_unsupported(data)
  165. super().test_merge(data, na_value)
  166. def test_get(self, data):
  167. ser = pd.Series(data, index=[2 * i for i in range(len(data))])
  168. if np.isnan(ser.values.fill_value):
  169. assert np.isnan(ser.get(4)) and np.isnan(ser.iloc[2])
  170. else:
  171. assert ser.get(4) == ser.iloc[2]
  172. assert ser.get(2) == ser.iloc[1]
  173. def test_reindex(self, data, na_value):
  174. self._check_unsupported(data)
  175. super().test_reindex(data, na_value)
  176. def test_isna(self, data_missing):
  177. sarr = SparseArray(data_missing)
  178. expected_dtype = SparseDtype(bool, pd.isna(data_missing.dtype.fill_value))
  179. expected = SparseArray([True, False], dtype=expected_dtype)
  180. result = sarr.isna()
  181. tm.assert_sp_array_equal(result, expected)
  182. # test isna for arr without na
  183. sarr = sarr.fillna(0)
  184. expected_dtype = SparseDtype(bool, pd.isna(data_missing.dtype.fill_value))
  185. expected = SparseArray([False, False], fill_value=False, dtype=expected_dtype)
  186. tm.assert_equal(sarr.isna(), expected)
  187. def test_fillna_limit_backfill(self, data_missing):
  188. warns = (PerformanceWarning, FutureWarning)
  189. with tm.assert_produces_warning(warns, check_stacklevel=False):
  190. super().test_fillna_limit_backfill(data_missing)
  191. def test_fillna_no_op_returns_copy(self, data, request):
  192. if np.isnan(data.fill_value):
  193. request.applymarker(
  194. pytest.mark.xfail(reason="returns array with different fill value")
  195. )
  196. super().test_fillna_no_op_returns_copy(data)
  197. @pytest.mark.xfail(reason="Unsupported")
  198. def test_fillna_series(self, data_missing):
  199. # this one looks doable.
  200. # TODO: this fails bc we do not pass through data_missing. If we did,
  201. # the 0-fill case would xpass
  202. super().test_fillna_series()
  203. def test_fillna_frame(self, data_missing):
  204. # Have to override to specify that fill_value will change.
  205. fill_value = data_missing[1]
  206. result = pd.DataFrame({"A": data_missing, "B": [1, 2]}).fillna(fill_value)
  207. if pd.isna(data_missing.fill_value):
  208. dtype = SparseDtype(data_missing.dtype, fill_value)
  209. else:
  210. dtype = data_missing.dtype
  211. expected = pd.DataFrame(
  212. {
  213. "A": data_missing._from_sequence([fill_value, fill_value], dtype=dtype),
  214. "B": [1, 2],
  215. }
  216. )
  217. tm.assert_frame_equal(result, expected)
  218. _combine_le_expected_dtype = "Sparse[bool]"
  219. def test_fillna_copy_frame(self, data_missing, using_copy_on_write):
  220. arr = data_missing.take([1, 1])
  221. df = pd.DataFrame({"A": arr}, copy=False)
  222. filled_val = df.iloc[0, 0]
  223. result = df.fillna(filled_val)
  224. if hasattr(df._mgr, "blocks"):
  225. if using_copy_on_write:
  226. assert df.values.base is result.values.base
  227. else:
  228. assert df.values.base is not result.values.base
  229. assert df.A._values.to_dense() is arr.to_dense()
  230. def test_fillna_copy_series(self, data_missing, using_copy_on_write):
  231. arr = data_missing.take([1, 1])
  232. ser = pd.Series(arr, copy=False)
  233. filled_val = ser[0]
  234. result = ser.fillna(filled_val)
  235. if using_copy_on_write:
  236. assert ser._values is result._values
  237. else:
  238. assert ser._values is not result._values
  239. assert ser._values.to_dense() is arr.to_dense()
  240. @pytest.mark.xfail(reason="Not Applicable")
  241. def test_fillna_length_mismatch(self, data_missing):
  242. super().test_fillna_length_mismatch(data_missing)
  243. def test_where_series(self, data, na_value):
  244. assert data[0] != data[1]
  245. cls = type(data)
  246. a, b = data[:2]
  247. ser = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype))
  248. cond = np.array([True, True, False, False])
  249. result = ser.where(cond)
  250. new_dtype = SparseDtype("float", 0.0)
  251. expected = pd.Series(
  252. cls._from_sequence([a, a, na_value, na_value], dtype=new_dtype)
  253. )
  254. tm.assert_series_equal(result, expected)
  255. other = cls._from_sequence([a, b, a, b], dtype=data.dtype)
  256. cond = np.array([True, False, True, True])
  257. result = ser.where(cond, other)
  258. expected = pd.Series(cls._from_sequence([a, b, b, b], dtype=data.dtype))
  259. tm.assert_series_equal(result, expected)
  260. def test_searchsorted(self, data_for_sorting, as_series):
  261. with tm.assert_produces_warning(PerformanceWarning, check_stacklevel=False):
  262. super().test_searchsorted(data_for_sorting, as_series)
  263. def test_shift_0_periods(self, data):
  264. # GH#33856 shifting with periods=0 should return a copy, not same obj
  265. result = data.shift(0)
  266. data._sparse_values[0] = data._sparse_values[1]
  267. assert result._sparse_values[0] != result._sparse_values[1]
  268. @pytest.mark.parametrize("method", ["argmax", "argmin"])
  269. def test_argmin_argmax_all_na(self, method, data, na_value):
  270. # overriding because Sparse[int64, 0] cannot handle na_value
  271. self._check_unsupported(data)
  272. super().test_argmin_argmax_all_na(method, data, na_value)
  273. @pytest.mark.fails_arm_wheels
  274. @pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame])
  275. def test_equals(self, data, na_value, as_series, box):
  276. self._check_unsupported(data)
  277. super().test_equals(data, na_value, as_series, box)
  278. @pytest.mark.fails_arm_wheels
  279. def test_equals_same_data_different_object(self, data):
  280. super().test_equals_same_data_different_object(data)
  281. @pytest.mark.parametrize(
  282. "func, na_action, expected",
  283. [
  284. (lambda x: x, None, SparseArray([1.0, np.nan])),
  285. (lambda x: x, "ignore", SparseArray([1.0, np.nan])),
  286. (str, None, SparseArray(["1.0", "nan"], fill_value="nan")),
  287. (str, "ignore", SparseArray(["1.0", np.nan])),
  288. ],
  289. )
  290. def test_map(self, func, na_action, expected):
  291. # GH52096
  292. data = SparseArray([1, np.nan])
  293. result = data.map(func, na_action=na_action)
  294. tm.assert_extension_array_equal(result, expected)
  295. @pytest.mark.parametrize("na_action", [None, "ignore"])
  296. def test_map_raises(self, data, na_action):
  297. # GH52096
  298. msg = "fill value in the sparse values not supported"
  299. with pytest.raises(ValueError, match=msg):
  300. data.map(lambda x: np.nan, na_action=na_action)
  301. @pytest.mark.xfail(raises=TypeError, reason="no sparse StringDtype")
  302. def test_astype_string(self, data, nullable_string_dtype):
  303. # TODO: this fails bc we do not pass through nullable_string_dtype;
  304. # If we did, the 0-cases would xpass
  305. super().test_astype_string(data)
  306. series_scalar_exc = None
  307. frame_scalar_exc = None
  308. divmod_exc = None
  309. series_array_exc = None
  310. def _skip_if_different_combine(self, data):
  311. if data.fill_value == 0:
  312. # arith ops call on dtype.fill_value so that the sparsity
  313. # is maintained. Combine can't be called on a dtype in
  314. # general, so we can't make the expected. This is tested elsewhere
  315. pytest.skip("Incorrected expected from Series.combine and tested elsewhere")
  316. def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
  317. self._skip_if_different_combine(data)
  318. super().test_arith_series_with_scalar(data, all_arithmetic_operators)
  319. def test_arith_series_with_array(self, data, all_arithmetic_operators):
  320. self._skip_if_different_combine(data)
  321. super().test_arith_series_with_array(data, all_arithmetic_operators)
  322. def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):
  323. if data.dtype.fill_value != 0:
  324. pass
  325. elif all_arithmetic_operators.strip("_") not in [
  326. "mul",
  327. "rmul",
  328. "floordiv",
  329. "rfloordiv",
  330. "pow",
  331. "mod",
  332. "rmod",
  333. ]:
  334. mark = pytest.mark.xfail(reason="result dtype.fill_value mismatch")
  335. request.applymarker(mark)
  336. super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
  337. def _compare_other(
  338. self, ser: pd.Series, data_for_compare: SparseArray, comparison_op, other
  339. ):
  340. op = comparison_op
  341. result = op(data_for_compare, other)
  342. if isinstance(other, pd.Series):
  343. assert isinstance(result, pd.Series)
  344. assert isinstance(result.dtype, SparseDtype)
  345. else:
  346. assert isinstance(result, SparseArray)
  347. assert result.dtype.subtype == np.bool_
  348. if isinstance(other, pd.Series):
  349. fill_value = op(data_for_compare.fill_value, other._values.fill_value)
  350. expected = SparseArray(
  351. op(data_for_compare.to_dense(), np.asarray(other)),
  352. fill_value=fill_value,
  353. dtype=np.bool_,
  354. )
  355. else:
  356. fill_value = np.all(
  357. op(np.asarray(data_for_compare.fill_value), np.asarray(other))
  358. )
  359. expected = SparseArray(
  360. op(data_for_compare.to_dense(), np.asarray(other)),
  361. fill_value=fill_value,
  362. dtype=np.bool_,
  363. )
  364. if isinstance(other, pd.Series):
  365. # error: Incompatible types in assignment
  366. expected = pd.Series(expected) # type: ignore[assignment]
  367. tm.assert_equal(result, expected)
  368. def test_scalar(self, data_for_compare: SparseArray, comparison_op):
  369. ser = pd.Series(data_for_compare)
  370. self._compare_other(ser, data_for_compare, comparison_op, 0)
  371. self._compare_other(ser, data_for_compare, comparison_op, 1)
  372. self._compare_other(ser, data_for_compare, comparison_op, -1)
  373. self._compare_other(ser, data_for_compare, comparison_op, np.nan)
  374. def test_array(self, data_for_compare: SparseArray, comparison_op, request):
  375. if data_for_compare.dtype.fill_value == 0 and comparison_op.__name__ in [
  376. "eq",
  377. "ge",
  378. "le",
  379. ]:
  380. mark = pytest.mark.xfail(reason="Wrong fill_value")
  381. request.applymarker(mark)
  382. arr = np.linspace(-4, 5, 10)
  383. ser = pd.Series(data_for_compare)
  384. self._compare_other(ser, data_for_compare, comparison_op, arr)
  385. def test_sparse_array(self, data_for_compare: SparseArray, comparison_op, request):
  386. if data_for_compare.dtype.fill_value == 0 and comparison_op.__name__ != "gt":
  387. mark = pytest.mark.xfail(reason="Wrong fill_value")
  388. request.applymarker(mark)
  389. ser = pd.Series(data_for_compare)
  390. arr = data_for_compare + 1
  391. self._compare_other(ser, data_for_compare, comparison_op, arr)
  392. arr = data_for_compare * 2
  393. self._compare_other(ser, data_for_compare, comparison_op, arr)
  394. @pytest.mark.xfail(reason="Different repr")
  395. def test_array_repr(self, data, size):
  396. super().test_array_repr(data, size)
  397. @pytest.mark.xfail(reason="result does not match expected")
  398. @pytest.mark.parametrize("as_index", [True, False])
  399. def test_groupby_extension_agg(self, as_index, data_for_grouping):
  400. super().test_groupby_extension_agg(as_index, data_for_grouping)
  401. def test_array_type_with_arg(dtype):
  402. assert dtype.construct_array_type() is SparseArray