|
23 | 23 | is_bool_dtype,
|
24 | 24 | is_list_like,
|
25 | 25 | is_string_dtype,
|
26 |
| - is_scalar, is_dtype_equal) |
| 26 | + is_scalar, is_dtype_equal, |
| 27 | + is_scipy_sparse) |
27 | 28 | from pandas.core.dtypes.cast import (
|
28 | 29 | maybe_convert_platform, maybe_promote,
|
29 | 30 | astype_nansafe, find_common_type)
|
@@ -164,11 +165,13 @@ class SparseArray(PandasObject, np.ndarray):
|
164 | 165 |
|
165 | 166 | Parameters
|
166 | 167 | ----------
|
167 |
| - data : {array-like (1-D), Series, SparseSeries, dict} |
| 168 | + data : {array-like (1-D), Series, SparseSeries, dict, \ |
| 169 | + scipy.sparse.spmatrix} |
168 | 170 | kind : {'block', 'integer'}
|
169 | 171 | fill_value : float
|
170 | 172 | Code for missing value. Defaults depends on dtype.
|
171 |
| - 0 for int dtype, False for bool dtype, and NaN for other dtypes |
| 173 | + 0 for int dtype or scipy sparse matrix, False for bool dtype, and NaN |
| 174 | + for other dtypes |
172 | 175 | sparse_index : {BlockIndex, IntIndex}, optional
|
173 | 176 | Only if you have one. Mainly used internally
|
174 | 177 |
|
@@ -197,17 +200,27 @@ def __new__(cls, data, sparse_index=None, index=None, kind='integer',
|
197 | 200 | values.fill(data)
|
198 | 201 | data = values
|
199 | 202 |
|
200 |
| - if isinstance(data, ABCSparseSeries): |
201 |
| - data = data.values |
202 |
| - is_sparse_array = isinstance(data, SparseArray) |
203 |
| - |
204 | 203 | if dtype is not None:
|
205 | 204 | dtype = np.dtype(dtype)
|
206 | 205 |
|
207 |
| - if is_sparse_array: |
| 206 | + if isinstance(data, ABCSparseSeries): |
| 207 | + data = data.values |
| 208 | + |
| 209 | + if isinstance(data, SparseArray): |
208 | 210 | sparse_index = data.sp_index
|
209 | 211 | values = data.sp_values
|
210 | 212 | fill_value = data.fill_value
|
| 213 | + elif is_scipy_sparse(data): |
| 214 | + if not any(ax == 1 for ax in data.shape): |
| 215 | + raise ValueError('Need 1D sparse matrix shaped ' |
| 216 | + '(n, 1) or (1, n)') |
| 217 | + coo = data.tocoo() |
| 218 | + values = coo.data |
| 219 | + indices = coo.row if coo.shape[0] != 1 else coo.col |
| 220 | + sparse_index = _make_index(max(coo.shape), indices, kind) |
| 221 | + # SciPy Sparse matrices imply missing value = 0 |
| 222 | + if fill_value is None: |
| 223 | + fill_value = 0 |
211 | 224 | else:
|
212 | 225 | # array-like
|
213 | 226 | if sparse_index is None:
|
|
0 commit comments