test_array.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import re
  2. import numpy as np
  3. import pytest
  4. from pandas._libs.sparse import IntIndex
  5. import pandas as pd
  6. from pandas import isna
  7. import pandas._testing as tm
  8. from pandas.core.arrays.sparse import (
  9. SparseArray,
  10. SparseDtype,
  11. )
  12. @pytest.fixture
  13. def arr_data():
  14. """Fixture returning numpy array with valid and missing entries"""
  15. return np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])
  16. @pytest.fixture
  17. def arr(arr_data):
  18. """Fixture returning SparseArray from 'arr_data'"""
  19. return SparseArray(arr_data)
  20. @pytest.fixture
  21. def zarr():
  22. """Fixture returning SparseArray with integer entries and 'fill_value=0'"""
  23. return SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0)
  24. class TestSparseArray:
  25. @pytest.mark.parametrize("fill_value", [0, None, np.nan])
  26. def test_shift_fill_value(self, fill_value):
  27. # GH #24128
  28. sparse = SparseArray(np.array([1, 0, 0, 3, 0]), fill_value=8.0)
  29. res = sparse.shift(1, fill_value=fill_value)
  30. if isna(fill_value):
  31. fill_value = res.dtype.na_value
  32. exp = SparseArray(np.array([fill_value, 1, 0, 0, 3]), fill_value=8.0)
  33. tm.assert_sp_array_equal(res, exp)
  34. def test_set_fill_value(self):
  35. arr = SparseArray([1.0, np.nan, 2.0], fill_value=np.nan)
  36. arr.fill_value = 2
  37. assert arr.fill_value == 2
  38. arr = SparseArray([1, 0, 2], fill_value=0, dtype=np.int64)
  39. arr.fill_value = 2
  40. assert arr.fill_value == 2
  41. # TODO: this seems fine? You can construct an integer
  42. # sparsearray with NaN fill value, why not update one?
  43. # coerces to int
  44. # msg = "unable to set fill_value 3\\.1 to int64 dtype"
  45. # with pytest.raises(ValueError, match=msg):
  46. arr.fill_value = 3.1
  47. assert arr.fill_value == 3.1
  48. # msg = "unable to set fill_value nan to int64 dtype"
  49. # with pytest.raises(ValueError, match=msg):
  50. arr.fill_value = np.nan
  51. assert np.isnan(arr.fill_value)
  52. arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)
  53. arr.fill_value = True
  54. assert arr.fill_value
  55. # FIXME: don't leave commented-out
  56. # coerces to bool
  57. # TODO: we can construct an sparse array of bool
  58. # type and use as fill_value any value
  59. # msg = "fill_value must be True, False or nan"
  60. # with pytest.raises(ValueError, match=msg):
  61. # arr.fill_value = 0
  62. # msg = "unable to set fill_value nan to bool dtype"
  63. # with pytest.raises(ValueError, match=msg):
  64. arr.fill_value = np.nan
  65. assert np.isnan(arr.fill_value)
  66. @pytest.mark.parametrize("val", [[1, 2, 3], np.array([1, 2]), (1, 2, 3)])
  67. def test_set_fill_invalid_non_scalar(self, val):
  68. arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)
  69. msg = "fill_value must be a scalar"
  70. with pytest.raises(ValueError, match=msg):
  71. arr.fill_value = val
  72. def test_copy(self, arr):
  73. arr2 = arr.copy()
  74. assert arr2.sp_values is not arr.sp_values
  75. assert arr2.sp_index is arr.sp_index
  76. def test_values_asarray(self, arr_data, arr):
  77. tm.assert_almost_equal(arr.to_dense(), arr_data)
  78. @pytest.mark.parametrize(
  79. "data,shape,dtype",
  80. [
  81. ([0, 0, 0, 0, 0], (5,), None),
  82. ([], (0,), None),
  83. ([0], (1,), None),
  84. (["A", "A", np.nan, "B"], (4,), object),
  85. ],
  86. )
  87. def test_shape(self, data, shape, dtype):
  88. # GH 21126
  89. out = SparseArray(data, dtype=dtype)
  90. assert out.shape == shape
  91. @pytest.mark.parametrize(
  92. "vals",
  93. [
  94. [np.nan, np.nan, np.nan, np.nan, np.nan],
  95. [1, np.nan, np.nan, 3, np.nan],
  96. [1, np.nan, 0, 3, 0],
  97. ],
  98. )
  99. @pytest.mark.parametrize("fill_value", [None, 0])
  100. def test_dense_repr(self, vals, fill_value):
  101. vals = np.array(vals)
  102. arr = SparseArray(vals, fill_value=fill_value)
  103. res = arr.to_dense()
  104. tm.assert_numpy_array_equal(res, vals)
  105. @pytest.mark.parametrize("fix", ["arr", "zarr"])
  106. def test_pickle(self, fix, request):
  107. obj = request.getfixturevalue(fix)
  108. unpickled = tm.round_trip_pickle(obj)
  109. tm.assert_sp_array_equal(unpickled, obj)
  110. def test_generator_warnings(self):
  111. sp_arr = SparseArray([1, 2, 3])
  112. with tm.assert_produces_warning(None):
  113. for _ in sp_arr:
  114. pass
  115. def test_where_retain_fill_value(self):
  116. # GH#45691 don't lose fill_value on _where
  117. arr = SparseArray([np.nan, 1.0], fill_value=0)
  118. mask = np.array([True, False])
  119. res = arr._where(~mask, 1)
  120. exp = SparseArray([1, 1.0], fill_value=0)
  121. tm.assert_sp_array_equal(res, exp)
  122. ser = pd.Series(arr)
  123. res = ser.where(~mask, 1)
  124. tm.assert_series_equal(res, pd.Series(exp))
  125. def test_fillna(self):
  126. s = SparseArray([1, np.nan, np.nan, 3, np.nan])
  127. res = s.fillna(-1)
  128. exp = SparseArray([1, -1, -1, 3, -1], fill_value=-1, dtype=np.float64)
  129. tm.assert_sp_array_equal(res, exp)
  130. s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0)
  131. res = s.fillna(-1)
  132. exp = SparseArray([1, -1, -1, 3, -1], fill_value=0, dtype=np.float64)
  133. tm.assert_sp_array_equal(res, exp)
  134. s = SparseArray([1, np.nan, 0, 3, 0])
  135. res = s.fillna(-1)
  136. exp = SparseArray([1, -1, 0, 3, 0], fill_value=-1, dtype=np.float64)
  137. tm.assert_sp_array_equal(res, exp)
  138. s = SparseArray([1, np.nan, 0, 3, 0], fill_value=0)
  139. res = s.fillna(-1)
  140. exp = SparseArray([1, -1, 0, 3, 0], fill_value=0, dtype=np.float64)
  141. tm.assert_sp_array_equal(res, exp)
  142. s = SparseArray([np.nan, np.nan, np.nan, np.nan])
  143. res = s.fillna(-1)
  144. exp = SparseArray([-1, -1, -1, -1], fill_value=-1, dtype=np.float64)
  145. tm.assert_sp_array_equal(res, exp)
  146. s = SparseArray([np.nan, np.nan, np.nan, np.nan], fill_value=0)
  147. res = s.fillna(-1)
  148. exp = SparseArray([-1, -1, -1, -1], fill_value=0, dtype=np.float64)
  149. tm.assert_sp_array_equal(res, exp)
  150. # float dtype's fill_value is np.nan, replaced by -1
  151. s = SparseArray([0.0, 0.0, 0.0, 0.0])
  152. res = s.fillna(-1)
  153. exp = SparseArray([0.0, 0.0, 0.0, 0.0], fill_value=-1)
  154. tm.assert_sp_array_equal(res, exp)
  155. # int dtype shouldn't have missing. No changes.
  156. s = SparseArray([0, 0, 0, 0])
  157. assert s.dtype == SparseDtype(np.int64)
  158. assert s.fill_value == 0
  159. res = s.fillna(-1)
  160. tm.assert_sp_array_equal(res, s)
  161. s = SparseArray([0, 0, 0, 0], fill_value=0)
  162. assert s.dtype == SparseDtype(np.int64)
  163. assert s.fill_value == 0
  164. res = s.fillna(-1)
  165. exp = SparseArray([0, 0, 0, 0], fill_value=0)
  166. tm.assert_sp_array_equal(res, exp)
  167. # fill_value can be nan if there is no missing hole.
  168. # only fill_value will be changed
  169. s = SparseArray([0, 0, 0, 0], fill_value=np.nan)
  170. assert s.dtype == SparseDtype(np.int64, fill_value=np.nan)
  171. assert np.isnan(s.fill_value)
  172. res = s.fillna(-1)
  173. exp = SparseArray([0, 0, 0, 0], fill_value=-1)
  174. tm.assert_sp_array_equal(res, exp)
  175. def test_fillna_overlap(self):
  176. s = SparseArray([1, np.nan, np.nan, 3, np.nan])
  177. # filling with existing value doesn't replace existing value with
  178. # fill_value, i.e. existing 3 remains in sp_values
  179. res = s.fillna(3)
  180. exp = np.array([1, 3, 3, 3, 3], dtype=np.float64)
  181. tm.assert_numpy_array_equal(res.to_dense(), exp)
  182. s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0)
  183. res = s.fillna(3)
  184. exp = SparseArray([1, 3, 3, 3, 3], fill_value=0, dtype=np.float64)
  185. tm.assert_sp_array_equal(res, exp)
  186. def test_nonzero(self):
  187. # Tests regression #21172.
  188. sa = SparseArray([float("nan"), float("nan"), 1, 0, 0, 2, 0, 0, 0, 3, 0, 0])
  189. expected = np.array([2, 5, 9], dtype=np.int32)
  190. (result,) = sa.nonzero()
  191. tm.assert_numpy_array_equal(expected, result)
  192. sa = SparseArray([0, 0, 1, 0, 0, 2, 0, 0, 0, 3, 0, 0])
  193. (result,) = sa.nonzero()
  194. tm.assert_numpy_array_equal(expected, result)
  195. class TestSparseArrayAnalytics:
  196. @pytest.mark.parametrize(
  197. "data,expected",
  198. [
  199. (
  200. np.array([1, 2, 3, 4, 5], dtype=float), # non-null data
  201. SparseArray(np.array([1.0, 3.0, 6.0, 10.0, 15.0])),
  202. ),
  203. (
  204. np.array([1, 2, np.nan, 4, 5], dtype=float), # null data
  205. SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0])),
  206. ),
  207. ],
  208. )
  209. @pytest.mark.parametrize("numpy", [True, False])
  210. def test_cumsum(self, data, expected, numpy):
  211. cumsum = np.cumsum if numpy else lambda s: s.cumsum()
  212. out = cumsum(SparseArray(data))
  213. tm.assert_sp_array_equal(out, expected)
  214. out = cumsum(SparseArray(data, fill_value=np.nan))
  215. tm.assert_sp_array_equal(out, expected)
  216. out = cumsum(SparseArray(data, fill_value=2))
  217. tm.assert_sp_array_equal(out, expected)
  218. if numpy: # numpy compatibility checks.
  219. msg = "the 'dtype' parameter is not supported"
  220. with pytest.raises(ValueError, match=msg):
  221. np.cumsum(SparseArray(data), dtype=np.int64)
  222. msg = "the 'out' parameter is not supported"
  223. with pytest.raises(ValueError, match=msg):
  224. np.cumsum(SparseArray(data), out=out)
  225. else:
  226. axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid.
  227. msg = re.escape(f"axis(={axis}) out of bounds")
  228. with pytest.raises(ValueError, match=msg):
  229. SparseArray(data).cumsum(axis=axis)
  230. def test_ufunc(self):
  231. # GH 13853 make sure ufunc is applied to fill_value
  232. sparse = SparseArray([1, np.nan, 2, np.nan, -2])
  233. result = SparseArray([1, np.nan, 2, np.nan, 2])
  234. tm.assert_sp_array_equal(abs(sparse), result)
  235. tm.assert_sp_array_equal(np.abs(sparse), result)
  236. sparse = SparseArray([1, -1, 2, -2], fill_value=1)
  237. result = SparseArray([1, 2, 2], sparse_index=sparse.sp_index, fill_value=1)
  238. tm.assert_sp_array_equal(abs(sparse), result)
  239. tm.assert_sp_array_equal(np.abs(sparse), result)
  240. sparse = SparseArray([1, -1, 2, -2], fill_value=-1)
  241. exp = SparseArray([1, 1, 2, 2], fill_value=1)
  242. tm.assert_sp_array_equal(abs(sparse), exp)
  243. tm.assert_sp_array_equal(np.abs(sparse), exp)
  244. sparse = SparseArray([1, np.nan, 2, np.nan, -2])
  245. result = SparseArray(np.sin([1, np.nan, 2, np.nan, -2]))
  246. tm.assert_sp_array_equal(np.sin(sparse), result)
  247. sparse = SparseArray([1, -1, 2, -2], fill_value=1)
  248. result = SparseArray(np.sin([1, -1, 2, -2]), fill_value=np.sin(1))
  249. tm.assert_sp_array_equal(np.sin(sparse), result)
  250. sparse = SparseArray([1, -1, 0, -2], fill_value=0)
  251. result = SparseArray(np.sin([1, -1, 0, -2]), fill_value=np.sin(0))
  252. tm.assert_sp_array_equal(np.sin(sparse), result)
  253. def test_ufunc_args(self):
  254. # GH 13853 make sure ufunc is applied to fill_value, including its arg
  255. sparse = SparseArray([1, np.nan, 2, np.nan, -2])
  256. result = SparseArray([2, np.nan, 3, np.nan, -1])
  257. tm.assert_sp_array_equal(np.add(sparse, 1), result)
  258. sparse = SparseArray([1, -1, 2, -2], fill_value=1)
  259. result = SparseArray([2, 0, 3, -1], fill_value=2)
  260. tm.assert_sp_array_equal(np.add(sparse, 1), result)
  261. sparse = SparseArray([1, -1, 0, -2], fill_value=0)
  262. result = SparseArray([2, 0, 1, -1], fill_value=1)
  263. tm.assert_sp_array_equal(np.add(sparse, 1), result)
  264. @pytest.mark.parametrize("fill_value", [0.0, np.nan])
  265. def test_modf(self, fill_value):
  266. # https://github.com/pandas-dev/pandas/issues/26946
  267. sparse = SparseArray([fill_value] * 10 + [1.1, 2.2], fill_value=fill_value)
  268. r1, r2 = np.modf(sparse)
  269. e1, e2 = np.modf(np.asarray(sparse))
  270. tm.assert_sp_array_equal(r1, SparseArray(e1, fill_value=fill_value))
  271. tm.assert_sp_array_equal(r2, SparseArray(e2, fill_value=fill_value))
  272. def test_nbytes_integer(self):
  273. arr = SparseArray([1, 0, 0, 0, 2], kind="integer")
  274. result = arr.nbytes
  275. # (2 * 8) + 2 * 4
  276. assert result == 24
  277. def test_nbytes_block(self):
  278. arr = SparseArray([1, 2, 0, 0, 0], kind="block")
  279. result = arr.nbytes
  280. # (2 * 8) + 4 + 4
  281. # sp_values, blocs, blengths
  282. assert result == 24
  283. def test_asarray_datetime64(self):
  284. s = SparseArray(pd.to_datetime(["2012", None, None, "2013"]))
  285. np.asarray(s)
  286. def test_density(self):
  287. arr = SparseArray([0, 1])
  288. assert arr.density == 0.5
  289. def test_npoints(self):
  290. arr = SparseArray([0, 1])
  291. assert arr.npoints == 1
  292. def test_setting_fill_value_fillna_still_works():
  293. # This is why letting users update fill_value / dtype is bad
  294. # astype has the same problem.
  295. arr = SparseArray([1.0, np.nan, 1.0], fill_value=0.0)
  296. arr.fill_value = np.nan
  297. result = arr.isna()
  298. # Can't do direct comparison, since the sp_index will be different
  299. # So let's convert to ndarray and check there.
  300. result = np.asarray(result)
  301. expected = np.array([False, True, False])
  302. tm.assert_numpy_array_equal(result, expected)
  303. def test_setting_fill_value_updates():
  304. arr = SparseArray([0.0, np.nan], fill_value=0)
  305. arr.fill_value = np.nan
  306. # use private constructor to get the index right
  307. # otherwise both nans would be un-stored.
  308. expected = SparseArray._simple_new(
  309. sparse_array=np.array([np.nan]),
  310. sparse_index=IntIndex(2, [1]),
  311. dtype=SparseDtype(float, np.nan),
  312. )
  313. tm.assert_sp_array_equal(arr, expected)
  314. @pytest.mark.parametrize(
  315. "arr,fill_value,loc",
  316. [
  317. ([None, 1, 2], None, 0),
  318. ([0, None, 2], None, 1),
  319. ([0, 1, None], None, 2),
  320. ([0, 1, 1, None, None], None, 3),
  321. ([1, 1, 1, 2], None, -1),
  322. ([], None, -1),
  323. ([None, 1, 0, 0, None, 2], None, 0),
  324. ([None, 1, 0, 0, None, 2], 1, 1),
  325. ([None, 1, 0, 0, None, 2], 2, 5),
  326. ([None, 1, 0, 0, None, 2], 3, -1),
  327. ([None, 0, 0, 1, 2, 1], 0, 1),
  328. ([None, 0, 0, 1, 2, 1], 1, 3),
  329. ],
  330. )
  331. def test_first_fill_value_loc(arr, fill_value, loc):
  332. result = SparseArray(arr, fill_value=fill_value)._first_fill_value_loc()
  333. assert result == loc
  334. @pytest.mark.parametrize(
  335. "arr",
  336. [
  337. [1, 2, np.nan, np.nan],
  338. [1, np.nan, 2, np.nan],
  339. [1, 2, np.nan],
  340. [np.nan, 1, 0, 0, np.nan, 2],
  341. [np.nan, 0, 0, 1, 2, 1],
  342. ],
  343. )
  344. @pytest.mark.parametrize("fill_value", [np.nan, 0, 1])
  345. def test_unique_na_fill(arr, fill_value):
  346. a = SparseArray(arr, fill_value=fill_value).unique()
  347. b = pd.Series(arr).unique()
  348. assert isinstance(a, SparseArray)
  349. a = np.asarray(a)
  350. tm.assert_numpy_array_equal(a, b)
  351. def test_unique_all_sparse():
  352. # https://github.com/pandas-dev/pandas/issues/23168
  353. arr = SparseArray([0, 0])
  354. result = arr.unique()
  355. expected = SparseArray([0])
  356. tm.assert_sp_array_equal(result, expected)
  357. def test_map():
  358. arr = SparseArray([0, 1, 2])
  359. expected = SparseArray([10, 11, 12], fill_value=10)
  360. # dict
  361. result = arr.map({0: 10, 1: 11, 2: 12})
  362. tm.assert_sp_array_equal(result, expected)
  363. # series
  364. result = arr.map(pd.Series({0: 10, 1: 11, 2: 12}))
  365. tm.assert_sp_array_equal(result, expected)
  366. # function
  367. result = arr.map(pd.Series({0: 10, 1: 11, 2: 12}))
  368. expected = SparseArray([10, 11, 12], fill_value=10)
  369. tm.assert_sp_array_equal(result, expected)
  370. def test_map_missing():
  371. arr = SparseArray([0, 1, 2])
  372. expected = SparseArray([10, 11, None], fill_value=10)
  373. result = arr.map({0: 10, 1: 11})
  374. tm.assert_sp_array_equal(result, expected)
  375. @pytest.mark.parametrize("fill_value", [np.nan, 1])
  376. def test_dropna(fill_value):
  377. # GH-28287
  378. arr = SparseArray([np.nan, 1], fill_value=fill_value)
  379. exp = SparseArray([1.0], fill_value=fill_value)
  380. tm.assert_sp_array_equal(arr.dropna(), exp)
  381. df = pd.DataFrame({"a": [0, 1], "b": arr})
  382. expected_df = pd.DataFrame({"a": [1], "b": exp}, index=pd.Index([1]))
  383. tm.assert_equal(df.dropna(), expected_df)
  384. def test_drop_duplicates_fill_value():
  385. # GH 11726
  386. df = pd.DataFrame(np.zeros((5, 5))).apply(lambda x: SparseArray(x, fill_value=0))
  387. result = df.drop_duplicates()
  388. expected = pd.DataFrame({i: SparseArray([0.0], fill_value=0) for i in range(5)})
  389. tm.assert_frame_equal(result, expected)