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.
In [1]: arr=np.random.randn(10)In [2]: arr[2:-2]=np
.
nan
In [3]:
ts
=
pd
.
Series
(
pd
.
arrays
.
SparseArray
(
arr
))
In [4]:
ts
Out[4]:
0 0.469112
1 -0.282863
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 -0.861849
9 -2.104569
dtype: Sparse[float64, nan]
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:
In [5]: df=pd.DataFrame(np.random.randn(10000,4))In [6]: df.iloc[:9998]=np.nanIn [7]: sdf=df.astype(pd.SparseDtype("float",np.nan))In [8]: sdf.head()Out[8]: 0 1 2 30 NaN NaN NaN NaN1 NaN NaN NaN NaN2 NaN NaN NaN NaN3 NaN NaN NaN NaN4 NaN NaN NaN NaNIn [9]: sdf.dtypesOut[9]: 0 Sparse[float64, nan]1 Sparse[float64, nan]2 Sparse[float64, nan]3 Sparse[float64, nan]dtype: objectIn [10]: sdf.sparse.densityOut[10]: 0.0002
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.
Functionally, their behavior should be nearly
identical to their dense counterparts.
SparseArray
arrays.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:
The SparseArray.dtype property stores two pieces of information
The dtype of the non-sparse values
The scalar fill value
In [19]: sparr.dtypeOut[19]: Sparse[float64, nan]
A SparseDtype may be constructed by passing only a dtype
In [20]: pd.SparseDtype(np.dtype('datetime64[ns]'))Out[20]: Sparse[datetime64[ns], numpy.datetime64('NaT')]
in which case a default fill value will be used (for NumPy dtypes this is often the
“missing” value for that dtype). To override this default an explicit fill value may be
passed instead
In [21]: pd.SparseDtype(np.dtype('datetime64[ns]'), ....: fill_value=pd.Timestamp('2017-01-01')) ....: Out[21]: Sparse[datetime64[ns], Timestamp('2017-01-01 00:00:00')]
Finally, the string alias 'Sparse[dtype]' may be used to specify a sparse dtype
in many places
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.
In [23]: s=pd.Series([0,0,1,2],dtype="Sparse[int]")In [24]: s.sparse.densityOut[24]: 0.5In [25]: s.sparse.fill_valueOut[25]: 0
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.
To convert data from sparse to dense, use the .sparse accessors
In [31]: sdf.sparse.to_dense()Out[31]: 0 1 2 30 NaN NaN NaN NaN1 NaN NaN NaN NaN2 NaN NaN NaN NaN3 NaN NaN NaN NaN4 NaN NaN NaN NaN... ... ... ... ...9995 NaN NaN NaN NaN9996 NaN NaN NaN NaN9997 NaN NaN NaN NaN9998 0.509184 -0.774928 -1.369894 -0.3821419999 0.280249 -1.648493 1.490865 -0.890819[10000 rows x 4 columns]
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:
In [43]: sdf.sparse.to_coo()Out[43]: <COOrdinate sparse matrix of dtype 'float64' with 517 stored elements and shape (1000, 5)>
The method requires a MultiIndex with two or more levels.
In [44]: s=pd.Series([3.0,np.nan,1.0,3.0,np.nan,np.nan])In [45]: s.index=pd.MultiIndex.from_tuples( ....: [
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.
In [48]: A,rows,columns=ss.sparse.to_coo( ....: row_levels=["A","B"],column_levels=["C","D"],sort_labels=True ....: ) ....: In [49]: AOut[49]:
Specifying different row and column labels (and not sorting them) yields a different sparse matrix:
In [53]: A,rows,columns=ss.sparse.to_coo( ....: row_levels=["A","B","C"],column_levels=["D"],sort_labels=False ....: ) ....: In [54]: AOut[54]:
A convenience method Series.sparse.from_coo() is implemented for creating a Series with sparse values from a scipy.sparse.coo_matrix.
In [58]: fromscipyimportsparseIn [59]: A=sparse.coo_matrix(([3.0,1.0,2.0],([1,0,0],[0,2,3])),shape=(3
The default behaviour (with dense_index=False) simply returns a Series containing
only the non-null entries.
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.
In [64]: ss_dense=pd.Series.sparse.from_coo(A,dense_index=True)In [65]: ss_denseOut[65]: 1 0 3.0 2 NaN 3 NaN0 0 NaN 2 1.0 3 2.0 0 NaN 2 1.0 3 2.0dtype: Sparse[float64, nan]