pandas 1.4.2

ParametersReturns
to_coo(self, row_levels=(0,), column_levels=(1,), sort_labels=False)

Use row_levels and column_levels to determine the row and column coordinates respectively. row_levels and column_levels are the names (labels) or numbers of the levels. {row_levels, column_levels} must be a partition of the MultiIndex level names (or numbers).

Parameters

row_levels : tuple/list
column_levels : tuple/list
sort_labels : bool, default False

Sort the row and column labels before forming the sparse matrix. When :None:None:`row_levels` and/or :None:None:`column_levels` refer to a single level, set to :None:None:`True` for a faster execution.

Returns

y : scipy.sparse.coo_matrix
rows : list (row labels)
columns : list (column labels)

Create a scipy.sparse.coo_matrix from a Series with MultiIndex.

Examples

This example is valid syntax, but we were not able to check execution
>>> s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan])
... s.index = pd.MultiIndex.from_tuples(
...  [
...  (1, 2, "a", 0),
...  (1, 2, "a", 1),
...  (1, 1, "b", 0),
...  (1, 1, "b", 1),
...  (2, 1, "b", 0),
...  (2, 1, "b", 1)
...  ],
...  names=["A", "B", "C", "D"],
... )
... s A B C D 1 2 a 0 3.0 1 NaN 1 b 0 1.0 1 3.0 2 1 b 0 NaN 1 NaN dtype: float64
This example is valid syntax, but we were not able to check execution
>>> ss = s.astype("Sparse")
... ss A B C D 1 2 a 0 3.0 1 NaN 1 b 0 1.0 1 3.0 2 1 b 0 NaN 1 NaN dtype: Sparse[float64, nan]
This example is valid syntax, but we were not able to check execution
>>> A, rows, columns = ss.sparse.to_coo(
...  row_levels=["A", "B"], column_levels=["C", "D"], sort_labels=True
... )
... A <3x4 sparse matrix of type '<class 'numpy.float64'>' with 3 stored elements in COOrdinate format>
This example is valid syntax, but we were not able to check execution
>>> A.todense()
matrix([[0., 0., 1., 3.],
[3., 0., 0., 0.],
[0., 0., 0., 0.]])
This example is valid syntax, but we were not able to check execution
>>> rows
[(1, 1), (1, 2), (2, 1)]
This example is valid syntax, but we were not able to check execution
>>> columns
[('a', 0), ('a', 1), ('b', 0), ('b', 1)]
See :

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


File: /pandas/core/arrays/sparse/accessor.py#101
type: <class 'function'>
Commit: