Skip to content

Commit 9d6d2fe

Browse files
committed
ENH: Series constructor supports 1d scipy.sparse.spmatrix input
1 parent 690a09f commit 9d6d2fe

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

pandas/core/sparse/series.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import warnings
1010

1111
from pandas.core.dtypes.missing import isnull, notnull
12-
from pandas.core.dtypes.common import is_scalar
12+
from pandas.core.dtypes.common import is_scalar, is_scipy_sparse
1313
from pandas.core.common import _values_from_object, _maybe_match_name
1414

1515
from pandas.compat.numpy import function as nv
@@ -90,7 +90,7 @@ class SparseSeries(Series):
9090
9191
Parameters
9292
----------
93-
data : {array-like, Series, SparseSeries, dict}
93+
data : {array-like, Series, SparseSeries, dict, scipy.sparse.spmatrix}
9494
kind : {'block', 'integer'}
9595
fill_value : float
9696
Code for missing value. Defaults depends on dtype.
@@ -128,6 +128,10 @@ def __init__(self, data=None, index=None, sparse_index=None, kind='block',
128128
if isinstance(data, Series) and name is None:
129129
name = data.name
130130

131+
if is_scipy_sparse(data):
132+
data = SparseArray(data, dtype=dtype, kind=kind,
133+
fill_value=fill_value)
134+
131135
if isinstance(data, SparseArray):
132136
if index is not None:
133137
assert (len(index) == len(data))

pandas/tests/sparse/test_series.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,24 @@ def test_constructor_preserve_attr(self):
142142
assert s.dtype == np.int64
143143
assert s.fill_value == 0
144144

145+
def test_constructor_spmatrix(self):
146+
# GH-15634
147+
tm.skip_if_no_package('scipy')
148+
from scipy.sparse import csr_matrix
149+
150+
spm = csr_matrix(np.eye(5)[:, 2])
151+
152+
arr = SparseSeries(spm)
153+
assert arr.dtype == spm.dtype
154+
assert arr.fill_value == 0
155+
156+
arr = SparseSeries(spm, kind='block', dtype=float, fill_value=np.nan)
157+
assert arr.dtype == float
158+
assert np.isnan(arr.fill_value)
159+
160+
tm.assert_raises_regex(ValueError, '1D',
161+
lambda: SparseSeries(csr_matrix(np.eye(3))))
162+
145163
def test_series_density(self):
146164
# GH2803
147165
ts = Series(np.random.randn(10))

0 commit comments

Comments
 (0)