sparse
Sparse data structures
::: tip Note
SparseSeries and SparseDataFrame have been deprecated. Their purpose
is served equally well by a Series or DataFrame with
sparse values. See Migrating for tips on migrating.
:::
Pandas provides data structures for efficiently storing sparse data.
These are not necessarily sparse in the typical “mostly 0”. Rather, you can view these
objects as being “compressed” where any data matching a specific value (NaN / missing value, though any value
can be chosen, including 0) is omitted. The compressed values are not actually stored in the array.
1 | In [1]: arr = np.random.randn(10) |
Notice the dtype, Sparse[float64, nan]. The nan means that elements in the
array that are nan aren’t actually stored, only the non-nan elements are.
Those non-nan elements have a float64 dtype.
The sparse objects exist for memory efficiency reasons. Suppose you had a
large, mostly NA DataFrame:
1 | In [5]: df = pd.DataFrame(np.random.randn(10000, 4)) |
As you can see, the density (% of values that have not been “compressed”) is
extremely low. This sparse object takes up much less memory on disk (pickled)
and in the Python interpreter.
1 | In [11]: 'dense : {:0.2f} bytes'.format(df.memory_usage().sum() / 1e3) |
Functionally, their behavior should be nearly
identical to their dense counterparts.
SparseArray
SparseArray is a ExtensionArray
for storing an array of sparse values (see dtypes for more
on extension arrays). It is a 1-dimensional ndarray-like object storing
only values distinct from the fill_value:
1 | In [13]: arr = np.random.randn(10) |
A sparse array can be converted to a regular (dense) ndarray with numpy.asarray()
1 | In [18]: np.asarray(sparr) |
SparseDtype
The SparseArray.dtype property stores two pieces of information
- The dtype of the non-sparse values
- The scalar fill value
1 | In [19]: sparr.dtype |
A SparseDtype may be constructed by passing each of these
1 | In [20]: pd.SparseDtype(np.dtype('datetime64[ns]')) |
The default fill value for a given NumPy dtype is the “missing” value for that dtype,
though it may be overridden.
1 | In [21]: pd.SparseDtype(np.dtype('datetime64[ns]'), |
Finally, the string alias 'Sparse[dtype]' may be used to specify a sparse dtype
in many places
1 | In [22]: pd.array([1, 0, 0, 2], dtype='Sparse[int]') |
Sparse accessor
New in version 0.24.0.
Pandas provides a .sparse accessor, similar to .str for string data, .cat
for categorical data, and .dt for datetime-like data. This namespace provides
attributes and methods that are specific to sparse data.
1 | In [23]: s = pd.Series([0, 0, 1, 2], dtype="Sparse[int]") |
This accessor is available only on data with SparseDtype, and on the Series
class itself for creating a Series with sparse data from a scipy COO matrix with.
New in version 0.25.0.
A .sparse accessor has been added for DataFrame as well.
See Sparse accessor for more.
Sparse calculation
You can apply NumPy ufuncs
to SparseArray and get a SparseArray as a result.
1 | In [26]: arr = pd.SparseArray([1., np.nan, np.nan, -2., np.nan]) |
The ufunc is also applied to fill_value. This is needed to get
the correct dense result.
1 | In [28]: arr = pd.SparseArray([1., -1, -1, -2., -1], fill_value=-1) |
Migrating
In older versions of pandas, the SparseSeries and SparseDataFrame classes (documented below)
were the preferred way to work with sparse data. With the advent of extension arrays, these subclasses
are no longer needed. Their purpose is better served by using a regular Series or DataFrame with
sparse values instead.
::: tip Note
There’s no performance or memory penalty to using a Series or DataFrame with sparse values,
rather than a SparseSeries or SparseDataFrame.
:::
This section provides some guidance on migrating your code to the new style. As a reminder,
you can use the python warnings module to control warnings. But we recommend modifying
your code, rather than ignoring the warning.
Construction
From an array-like, use the regular Series orDataFrame constructors with SparseArray values.
1 | # Previous way |
1 | # New way |
From a SciPy sparse matrix, use DataFrame.sparse.from_spmatrix(),
1 | # Previous way |
1 | # New way |
Conversion
From sparse to dense, use the .sparse accessors
1 | In [36]: df.sparse.to_dense() |
From dense to sparse, use DataFrame.astype() with a SparseDtype.
1 | In [38]: dense = pd.DataFrame({"A": [1, 0, 0, 1]}) |
Sparse Properties
Sparse-specific properties, like density, are available on the .sparse accessor.
1 | In [41]: df.sparse.density |
General differences
In a SparseDataFrame, all columns were sparse. A DataFrame can have a mixture of
sparse and dense columns. As a consequence, assigning new columns to a DataFrame with sparse
values will not automatically convert the input to be sparse.
1 | # Previous Way |
Instead, you’ll need to ensure that the values being assigned are sparse
1 | In [42]: df = pd.DataFrame({"A": pd.SparseArray([0, 1])}) |
The SparseDataFrame.default_kind and SparseDataFrame.default_fill_value attributes
have no replacement.
Interaction with scipy.sparse
Use DataFrame.sparse.from_spmatrix() to create a DataFrame with sparse values from a sparse matrix.
New in version 0.25.0.
1 | In [47]: from scipy.sparse import csr_matrix |
All sparse formats are supported, but matrices that are not in COOrdinate format will be converted, copying data as needed.
To convert back to sparse SciPy matrix in COO format, you can use the DataFrame.sparse.to_coo() method:
1 | In [55]: sdf.sparse.to_coo() |
meth:Series.sparse.to_coo is implemented for transforming a Series with sparse values indexed by a MultiIndex to a scipy.sparse.coo_matrix.
The method requires a MultiIndex with two or more levels.
1 | In [56]: s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan]) |
In the example below, we transform the Series to a sparse representation of a 2-d array by specifying that the first and second MultiIndex levels define labels for the rows and the third and fourth levels define labels for the columns. We also specify that the column and row labels should be sorted in the final sparse representation.
1 | In [61]: A, rows, columns = ss.sparse.to_coo(row_levels=['A', 'B'], |
Specifying different row and column labels (and not sorting them) yields a different sparse matrix:
1 | In [66]: A, rows, columns = ss.sparse.to_coo(row_levels=['A', 'B', 'C'], |
A convenience method Series.sparse.from_coo() is implemented for creating a Series with sparse values from a scipy.sparse.coo_matrix.
1 | In [71]: from scipy import sparse |
The default behaviour (with dense_index=False) simply returns a Series containing
only the non-null entries.
1 | In [75]: ss = pd.Series.sparse.from_coo(A) |
Specifying dense_index=True will result in an index that is the Cartesian product of the
row and columns coordinates of the matrix. Note that this will consume a significant amount of memory
(relative to dense_index=False) if the sparse matrix is large (and sparse) enough.
1 | In [77]: ss_dense = pd.Series.sparse.from_coo(A, dense_index=True) |
Sparse subclasses
The SparseSeries and SparseDataFrame classes are deprecated. Visit their
API pages for usage.




