test_sparse.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import numpy as np
  2. import pytest
  3. from pandas.errors import PerformanceWarning
  4. import pandas as pd
  5. from pandas import SparseArray, SparseDtype
  6. from pandas.tests.extension import base
  7. import pandas.util.testing as tm
  8. def make_data(fill_value):
  9. if np.isnan(fill_value):
  10. data = np.random.uniform(size=100)
  11. else:
  12. data = np.random.randint(1, 100, size=100)
  13. if data[0] == data[1]:
  14. data[0] += 1
  15. data[2::3] = fill_value
  16. return data
  17. @pytest.fixture
  18. def dtype():
  19. return SparseDtype()
  20. @pytest.fixture(params=[0, np.nan])
  21. def data(request):
  22. """Length-100 PeriodArray for semantics test."""
  23. res = SparseArray(make_data(request.param),
  24. fill_value=request.param)
  25. return res
  26. @pytest.fixture(params=[0, np.nan])
  27. def data_missing(request):
  28. """Length 2 array with [NA, Valid]"""
  29. return SparseArray([np.nan, 1], fill_value=request.param)
  30. @pytest.fixture(params=[0, np.nan])
  31. def data_repeated(request):
  32. """Return different versions of data for count times"""
  33. def gen(count):
  34. for _ in range(count):
  35. yield SparseArray(make_data(request.param),
  36. fill_value=request.param)
  37. yield gen
  38. @pytest.fixture(params=[0, np.nan])
  39. def data_for_sorting(request):
  40. return SparseArray([2, 3, 1], fill_value=request.param)
  41. @pytest.fixture(params=[0, np.nan])
  42. def data_missing_for_sorting(request):
  43. return SparseArray([2, np.nan, 1], fill_value=request.param)
  44. @pytest.fixture
  45. def na_value():
  46. return np.nan
  47. @pytest.fixture
  48. def na_cmp():
  49. return lambda left, right: pd.isna(left) and pd.isna(right)
  50. @pytest.fixture(params=[0, np.nan])
  51. def data_for_grouping(request):
  52. return SparseArray([1, 1, np.nan, np.nan, 2, 2, 1, 3],
  53. fill_value=request.param)
  54. class BaseSparseTests(object):
  55. def _check_unsupported(self, data):
  56. if data.dtype == SparseDtype(int, 0):
  57. pytest.skip("Can't store nan in int array.")
  58. class TestDtype(BaseSparseTests, base.BaseDtypeTests):
  59. def test_array_type_with_arg(self, data, dtype):
  60. assert dtype.construct_array_type() is SparseArray
  61. class TestInterface(BaseSparseTests, base.BaseInterfaceTests):
  62. def test_no_values_attribute(self, data):
  63. pytest.skip("We have values")
  64. class TestConstructors(BaseSparseTests, base.BaseConstructorsTests):
  65. pass
  66. class TestReshaping(BaseSparseTests, base.BaseReshapingTests):
  67. def test_concat_mixed_dtypes(self, data):
  68. # https://github.com/pandas-dev/pandas/issues/20762
  69. # This should be the same, aside from concat([sparse, float])
  70. df1 = pd.DataFrame({'A': data[:3]})
  71. df2 = pd.DataFrame({"A": [1, 2, 3]})
  72. df3 = pd.DataFrame({"A": ['a', 'b', 'c']}).astype('category')
  73. dfs = [df1, df2, df3]
  74. # dataframes
  75. result = pd.concat(dfs)
  76. expected = pd.concat([x.apply(lambda s: np.asarray(s).astype(object))
  77. for x in dfs])
  78. self.assert_frame_equal(result, expected)
  79. def test_concat_columns(self, data, na_value):
  80. self._check_unsupported(data)
  81. super(TestReshaping, self).test_concat_columns(data, na_value)
  82. def test_align(self, data, na_value):
  83. self._check_unsupported(data)
  84. super(TestReshaping, self).test_align(data, na_value)
  85. def test_align_frame(self, data, na_value):
  86. self._check_unsupported(data)
  87. super(TestReshaping, self).test_align_frame(data, na_value)
  88. def test_align_series_frame(self, data, na_value):
  89. self._check_unsupported(data)
  90. super(TestReshaping, self).test_align_series_frame(data, na_value)
  91. def test_merge(self, data, na_value):
  92. self._check_unsupported(data)
  93. super(TestReshaping, self).test_merge(data, na_value)
  94. class TestGetitem(BaseSparseTests, base.BaseGetitemTests):
  95. def test_get(self, data):
  96. s = pd.Series(data, index=[2 * i for i in range(len(data))])
  97. if np.isnan(s.values.fill_value):
  98. assert np.isnan(s.get(4)) and np.isnan(s.iloc[2])
  99. else:
  100. assert s.get(4) == s.iloc[2]
  101. assert s.get(2) == s.iloc[1]
  102. def test_reindex(self, data, na_value):
  103. self._check_unsupported(data)
  104. super(TestGetitem, self).test_reindex(data, na_value)
  105. # Skipping TestSetitem, since we don't implement it.
  106. class TestMissing(BaseSparseTests, base.BaseMissingTests):
  107. def test_isna(self, data_missing):
  108. expected_dtype = SparseDtype(bool,
  109. pd.isna(data_missing.dtype.fill_value))
  110. expected = SparseArray([True, False], dtype=expected_dtype)
  111. result = pd.isna(data_missing)
  112. self.assert_equal(result, expected)
  113. result = pd.Series(data_missing).isna()
  114. expected = pd.Series(expected)
  115. self.assert_series_equal(result, expected)
  116. # GH 21189
  117. result = pd.Series(data_missing).drop([0, 1]).isna()
  118. expected = pd.Series([], dtype=expected_dtype)
  119. self.assert_series_equal(result, expected)
  120. def test_fillna_limit_pad(self, data_missing):
  121. with tm.assert_produces_warning(PerformanceWarning):
  122. super(TestMissing, self).test_fillna_limit_pad(data_missing)
  123. def test_fillna_limit_backfill(self, data_missing):
  124. with tm.assert_produces_warning(PerformanceWarning):
  125. super(TestMissing, self).test_fillna_limit_backfill(data_missing)
  126. def test_fillna_series_method(self, data_missing):
  127. with tm.assert_produces_warning(PerformanceWarning):
  128. super(TestMissing, self).test_fillna_limit_backfill(data_missing)
  129. @pytest.mark.skip(reason="Unsupported")
  130. def test_fillna_series(self):
  131. # this one looks doable.
  132. pass
  133. def test_fillna_frame(self, data_missing):
  134. # Have to override to specify that fill_value will change.
  135. fill_value = data_missing[1]
  136. result = pd.DataFrame({
  137. "A": data_missing,
  138. "B": [1, 2]
  139. }).fillna(fill_value)
  140. if pd.isna(data_missing.fill_value):
  141. dtype = SparseDtype(data_missing.dtype, fill_value)
  142. else:
  143. dtype = data_missing.dtype
  144. expected = pd.DataFrame({
  145. "A": data_missing._from_sequence([fill_value, fill_value],
  146. dtype=dtype),
  147. "B": [1, 2],
  148. })
  149. self.assert_frame_equal(result, expected)
  150. class TestMethods(BaseSparseTests, base.BaseMethodsTests):
  151. def test_combine_le(self, data_repeated):
  152. # We return a Series[SparseArray].__le__ returns a
  153. # Series[Sparse[bool]]
  154. # rather than Series[bool]
  155. orig_data1, orig_data2 = data_repeated(2)
  156. s1 = pd.Series(orig_data1)
  157. s2 = pd.Series(orig_data2)
  158. result = s1.combine(s2, lambda x1, x2: x1 <= x2)
  159. expected = pd.Series(pd.SparseArray([
  160. a <= b for (a, b) in
  161. zip(list(orig_data1), list(orig_data2))
  162. ], fill_value=False))
  163. self.assert_series_equal(result, expected)
  164. val = s1.iloc[0]
  165. result = s1.combine(val, lambda x1, x2: x1 <= x2)
  166. expected = pd.Series(pd.SparseArray([
  167. a <= val for a in list(orig_data1)
  168. ], fill_value=False))
  169. self.assert_series_equal(result, expected)
  170. def test_fillna_copy_frame(self, data_missing):
  171. arr = data_missing.take([1, 1])
  172. df = pd.DataFrame({"A": arr})
  173. filled_val = df.iloc[0, 0]
  174. result = df.fillna(filled_val)
  175. assert df.values.base is not result.values.base
  176. assert df.A._values.to_dense() is arr.to_dense()
  177. def test_fillna_copy_series(self, data_missing):
  178. arr = data_missing.take([1, 1])
  179. ser = pd.Series(arr)
  180. filled_val = ser[0]
  181. result = ser.fillna(filled_val)
  182. assert ser._values is not result._values
  183. assert ser._values.to_dense() is arr.to_dense()
  184. @pytest.mark.skip(reason="Not Applicable")
  185. def test_fillna_length_mismatch(self, data_missing):
  186. pass
  187. def test_where_series(self, data, na_value):
  188. assert data[0] != data[1]
  189. cls = type(data)
  190. a, b = data[:2]
  191. ser = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype))
  192. cond = np.array([True, True, False, False])
  193. result = ser.where(cond)
  194. new_dtype = SparseDtype('float', 0.0)
  195. expected = pd.Series(cls._from_sequence([a, a, na_value, na_value],
  196. dtype=new_dtype))
  197. self.assert_series_equal(result, expected)
  198. other = cls._from_sequence([a, b, a, b], dtype=data.dtype)
  199. cond = np.array([True, False, True, True])
  200. result = ser.where(cond, other)
  201. expected = pd.Series(cls._from_sequence([a, b, b, b],
  202. dtype=data.dtype))
  203. self.assert_series_equal(result, expected)
  204. def test_combine_first(self, data):
  205. if data.dtype.subtype == 'int':
  206. # Right now this is upcasted to float, just like combine_first
  207. # for Series[int]
  208. pytest.skip("TODO(SparseArray.__setitem__ will preserve dtype.")
  209. super(TestMethods, self).test_combine_first(data)
  210. @pytest.mark.parametrize("as_series", [True, False])
  211. def test_searchsorted(self, data_for_sorting, as_series):
  212. with tm.assert_produces_warning(PerformanceWarning):
  213. super(TestMethods, self).test_searchsorted(data_for_sorting,
  214. as_series=as_series)
  215. class TestCasting(BaseSparseTests, base.BaseCastingTests):
  216. pass
  217. class TestArithmeticOps(BaseSparseTests, base.BaseArithmeticOpsTests):
  218. series_scalar_exc = None
  219. frame_scalar_exc = None
  220. divmod_exc = None
  221. series_array_exc = None
  222. def _skip_if_different_combine(self, data):
  223. if data.fill_value == 0:
  224. # arith ops call on dtype.fill_value so that the sparsity
  225. # is maintained. Combine can't be called on a dtype in
  226. # general, so we can't make the expected. This is tested elsewhere
  227. raise pytest.skip("Incorrected expected from Series.combine")
  228. def test_error(self, data, all_arithmetic_operators):
  229. pass
  230. def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
  231. self._skip_if_different_combine(data)
  232. super(TestArithmeticOps, self).test_arith_series_with_scalar(
  233. data,
  234. all_arithmetic_operators
  235. )
  236. def test_arith_series_with_array(self, data, all_arithmetic_operators):
  237. self._skip_if_different_combine(data)
  238. super(TestArithmeticOps, self).test_arith_series_with_array(
  239. data,
  240. all_arithmetic_operators
  241. )
  242. class TestComparisonOps(BaseSparseTests, base.BaseComparisonOpsTests):
  243. def _compare_other(self, s, data, op_name, other):
  244. op = self.get_op_from_name(op_name)
  245. # array
  246. result = pd.Series(op(data, other))
  247. # hard to test the fill value, since we don't know what expected
  248. # is in general.
  249. # Rely on tests in `tests/sparse` to validate that.
  250. assert isinstance(result.dtype, SparseDtype)
  251. assert result.dtype.subtype == np.dtype('bool')
  252. with np.errstate(all='ignore'):
  253. expected = pd.Series(
  254. pd.SparseArray(op(np.asarray(data), np.asarray(other)),
  255. fill_value=result.values.fill_value)
  256. )
  257. tm.assert_series_equal(result, expected)
  258. # series
  259. s = pd.Series(data)
  260. result = op(s, other)
  261. tm.assert_series_equal(result, expected)
  262. class TestPrinting(BaseSparseTests, base.BasePrintingTests):
  263. @pytest.mark.xfail(reason='Different repr', strict=True)
  264. def test_array_repr(self, data, size):
  265. super(TestPrinting, self).test_array_repr(data, size)
  266. class TestParsing(BaseSparseTests, base.BaseParsingTests):
  267. @pytest.mark.parametrize('engine', ['c', 'python'])
  268. def test_EA_types(self, engine, data):
  269. expected_msg = r'.*must implement _from_sequence_of_strings.*'
  270. with pytest.raises(NotImplementedError, match=expected_msg):
  271. super(TestParsing, self).test_EA_types(engine, data)