test_accessor.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import string
  2. import numpy as np
  3. import pytest
  4. import pandas.util._test_decorators as td
  5. import pandas as pd
  6. import pandas._testing as tm
  7. from pandas.core.arrays.sparse import (
  8. SparseArray,
  9. SparseDtype,
  10. )
  11. class TestSeriesAccessor:
  12. def test_to_dense(self):
  13. ser = pd.Series([0, 1, 0, 10], dtype="Sparse[int64]")
  14. result = ser.sparse.to_dense()
  15. expected = pd.Series([0, 1, 0, 10])
  16. tm.assert_series_equal(result, expected)
  17. @pytest.mark.parametrize("attr", ["npoints", "density", "fill_value", "sp_values"])
  18. def test_get_attributes(self, attr):
  19. arr = SparseArray([0, 1])
  20. ser = pd.Series(arr)
  21. result = getattr(ser.sparse, attr)
  22. expected = getattr(arr, attr)
  23. assert result == expected
  24. @td.skip_if_no_scipy
  25. def test_from_coo(self):
  26. import scipy.sparse
  27. row = [0, 3, 1, 0]
  28. col = [0, 3, 1, 2]
  29. data = [4, 5, 7, 9]
  30. # TODO(scipy#13585): Remove dtype when scipy is fixed
  31. # https://github.com/scipy/scipy/issues/13585
  32. sp_array = scipy.sparse.coo_matrix((data, (row, col)), dtype="int")
  33. result = pd.Series.sparse.from_coo(sp_array)
  34. index = pd.MultiIndex.from_arrays(
  35. [
  36. np.array([0, 0, 1, 3], dtype=np.int32),
  37. np.array([0, 2, 1, 3], dtype=np.int32),
  38. ],
  39. )
  40. expected = pd.Series([4, 9, 7, 5], index=index, dtype="Sparse[int]")
  41. tm.assert_series_equal(result, expected)
  42. @td.skip_if_no_scipy
  43. @pytest.mark.parametrize(
  44. "sort_labels, expected_rows, expected_cols, expected_values_pos",
  45. [
  46. (
  47. False,
  48. [("b", 2), ("a", 2), ("b", 1), ("a", 1)],
  49. [("z", 1), ("z", 2), ("x", 2), ("z", 0)],
  50. {1: (1, 0), 3: (3, 3)},
  51. ),
  52. (
  53. True,
  54. [("a", 1), ("a", 2), ("b", 1), ("b", 2)],
  55. [("x", 2), ("z", 0), ("z", 1), ("z", 2)],
  56. {1: (1, 2), 3: (0, 1)},
  57. ),
  58. ],
  59. )
  60. def test_to_coo(
  61. self, sort_labels, expected_rows, expected_cols, expected_values_pos
  62. ):
  63. import scipy.sparse
  64. values = SparseArray([0, np.nan, 1, 0, None, 3], fill_value=0)
  65. index = pd.MultiIndex.from_tuples(
  66. [
  67. ("b", 2, "z", 1),
  68. ("a", 2, "z", 2),
  69. ("a", 2, "z", 1),
  70. ("a", 2, "x", 2),
  71. ("b", 1, "z", 1),
  72. ("a", 1, "z", 0),
  73. ]
  74. )
  75. ss = pd.Series(values, index=index)
  76. expected_A = np.zeros((4, 4))
  77. for value, (row, col) in expected_values_pos.items():
  78. expected_A[row, col] = value
  79. A, rows, cols = ss.sparse.to_coo(
  80. row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels
  81. )
  82. assert isinstance(A, scipy.sparse.coo_matrix)
  83. tm.assert_numpy_array_equal(A.toarray(), expected_A)
  84. assert rows == expected_rows
  85. assert cols == expected_cols
  86. def test_non_sparse_raises(self):
  87. ser = pd.Series([1, 2, 3])
  88. with pytest.raises(AttributeError, match=".sparse"):
  89. ser.sparse.density
  90. class TestFrameAccessor:
  91. def test_accessor_raises(self):
  92. df = pd.DataFrame({"A": [0, 1]})
  93. with pytest.raises(AttributeError, match="sparse"):
  94. df.sparse
  95. @pytest.mark.parametrize("format", ["csc", "csr", "coo"])
  96. @pytest.mark.parametrize("labels", [None, list(string.ascii_letters[:10])])
  97. @pytest.mark.parametrize("dtype", ["float64", "int64"])
  98. @td.skip_if_no_scipy
  99. def test_from_spmatrix(self, format, labels, dtype):
  100. import scipy.sparse
  101. sp_dtype = SparseDtype(dtype, np.array(0, dtype=dtype).item())
  102. mat = scipy.sparse.eye(10, format=format, dtype=dtype)
  103. result = pd.DataFrame.sparse.from_spmatrix(mat, index=labels, columns=labels)
  104. expected = pd.DataFrame(
  105. np.eye(10, dtype=dtype), index=labels, columns=labels
  106. ).astype(sp_dtype)
  107. tm.assert_frame_equal(result, expected)
  108. @pytest.mark.parametrize("format", ["csc", "csr", "coo"])
  109. @td.skip_if_no_scipy
  110. def test_from_spmatrix_including_explicit_zero(self, format):
  111. import scipy.sparse
  112. mat = scipy.sparse.random(10, 2, density=0.5, format=format)
  113. mat.data[0] = 0
  114. result = pd.DataFrame.sparse.from_spmatrix(mat)
  115. dtype = SparseDtype("float64", 0.0)
  116. expected = pd.DataFrame(mat.todense()).astype(dtype)
  117. tm.assert_frame_equal(result, expected)
  118. @pytest.mark.parametrize(
  119. "columns",
  120. [["a", "b"], pd.MultiIndex.from_product([["A"], ["a", "b"]]), ["a", "a"]],
  121. )
  122. @td.skip_if_no_scipy
  123. def test_from_spmatrix_columns(self, columns):
  124. import scipy.sparse
  125. dtype = SparseDtype("float64", 0.0)
  126. mat = scipy.sparse.random(10, 2, density=0.5)
  127. result = pd.DataFrame.sparse.from_spmatrix(mat, columns=columns)
  128. expected = pd.DataFrame(mat.toarray(), columns=columns).astype(dtype)
  129. tm.assert_frame_equal(result, expected)
  130. @pytest.mark.parametrize(
  131. "colnames", [("A", "B"), (1, 2), (1, pd.NA), (0.1, 0.2), ("x", "x"), (0, 0)]
  132. )
  133. @td.skip_if_no_scipy
  134. def test_to_coo(self, colnames):
  135. import scipy.sparse
  136. df = pd.DataFrame(
  137. {colnames[0]: [0, 1, 0], colnames[1]: [1, 0, 0]}, dtype="Sparse[int64, 0]"
  138. )
  139. result = df.sparse.to_coo()
  140. expected = scipy.sparse.coo_matrix(np.asarray(df))
  141. assert (result != expected).nnz == 0
  142. @pytest.mark.parametrize("fill_value", [1, np.nan])
  143. @td.skip_if_no_scipy
  144. def test_to_coo_nonzero_fill_val_raises(self, fill_value):
  145. df = pd.DataFrame(
  146. {
  147. "A": SparseArray(
  148. [fill_value, fill_value, fill_value, 2], fill_value=fill_value
  149. ),
  150. "B": SparseArray(
  151. [fill_value, 2, fill_value, fill_value], fill_value=fill_value
  152. ),
  153. }
  154. )
  155. with pytest.raises(ValueError, match="fill value must be 0"):
  156. df.sparse.to_coo()
  157. @td.skip_if_no_scipy
  158. def test_to_coo_midx_categorical(self):
  159. # GH#50996
  160. import scipy.sparse
  161. midx = pd.MultiIndex.from_arrays(
  162. [
  163. pd.CategoricalIndex(list("ab"), name="x"),
  164. pd.CategoricalIndex([0, 1], name="y"),
  165. ]
  166. )
  167. ser = pd.Series(1, index=midx, dtype="Sparse[int]")
  168. result = ser.sparse.to_coo(row_levels=["x"], column_levels=["y"])[0]
  169. expected = scipy.sparse.coo_matrix(
  170. (np.array([1, 1]), (np.array([0, 1]), np.array([0, 1]))), shape=(2, 2)
  171. )
  172. assert (result != expected).nnz == 0
  173. def test_to_dense(self):
  174. df = pd.DataFrame(
  175. {
  176. "A": SparseArray([1, 0], dtype=SparseDtype("int64", 0)),
  177. "B": SparseArray([1, 0], dtype=SparseDtype("int64", 1)),
  178. "C": SparseArray([1.0, 0.0], dtype=SparseDtype("float64", 0.0)),
  179. },
  180. index=["b", "a"],
  181. )
  182. result = df.sparse.to_dense()
  183. expected = pd.DataFrame(
  184. {"A": [1, 0], "B": [1, 0], "C": [1.0, 0.0]}, index=["b", "a"]
  185. )
  186. tm.assert_frame_equal(result, expected)
  187. def test_density(self):
  188. df = pd.DataFrame(
  189. {
  190. "A": SparseArray([1, 0, 2, 1], fill_value=0),
  191. "B": SparseArray([0, 1, 1, 1], fill_value=0),
  192. }
  193. )
  194. res = df.sparse.density
  195. expected = 0.75
  196. assert res == expected
  197. @pytest.mark.parametrize("dtype", ["int64", "float64"])
  198. @pytest.mark.parametrize("dense_index", [True, False])
  199. @td.skip_if_no_scipy
  200. def test_series_from_coo(self, dtype, dense_index):
  201. import scipy.sparse
  202. A = scipy.sparse.eye(3, format="coo", dtype=dtype)
  203. result = pd.Series.sparse.from_coo(A, dense_index=dense_index)
  204. index = pd.MultiIndex.from_tuples(
  205. [
  206. np.array([0, 0], dtype=np.int32),
  207. np.array([1, 1], dtype=np.int32),
  208. np.array([2, 2], dtype=np.int32),
  209. ],
  210. )
  211. expected = pd.Series(SparseArray(np.array([1, 1, 1], dtype=dtype)), index=index)
  212. if dense_index:
  213. expected = expected.reindex(pd.MultiIndex.from_product(index.levels))
  214. tm.assert_series_equal(result, expected)
  215. @td.skip_if_no_scipy
  216. def test_series_from_coo_incorrect_format_raises(self):
  217. # gh-26554
  218. import scipy.sparse
  219. m = scipy.sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
  220. with pytest.raises(
  221. TypeError, match="Expected coo_matrix. Got csr_matrix instead."
  222. ):
  223. pd.Series.sparse.from_coo(m)
  224. def test_with_column_named_sparse(self):
  225. # https://github.com/pandas-dev/pandas/issues/30758
  226. df = pd.DataFrame({"sparse": pd.arrays.SparseArray([1, 2])})
  227. assert isinstance(df.sparse, pd.core.arrays.sparse.accessor.SparseFrameAccessor)