Skip to content

as_coo

Converts any given format to sparse.COO. See the "See Also" section for details.

Parameters:

Name Type Description Default
x SparseArray or numpy.ndarray or scipy.sparse.spmatrix or Iterable.

The item to convert.

required
shape tuple[int]

The shape of the output array. Can only be used in case of Iterable.

None

Returns:

Name Type Description
out COO

The converted sparse.COO array.

See Also
Source code in sparse/numba_backend/_coo/core.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
def as_coo(x, shape=None, fill_value=None, idx_dtype=None):
    """
    Converts any given format to [`sparse.COO`][]. See the "See Also" section for details.

    Parameters
    ----------
    x : SparseArray or numpy.ndarray or scipy.sparse.spmatrix or Iterable.
        The item to convert.
    shape : tuple[int], optional
        The shape of the output array. Can only be used in case of Iterable.

    Returns
    -------
    out : COO
        The converted [`sparse.COO`][] array.

    See Also
    --------
    - [`sparse.SparseArray.asformat`][] :
        A utility function to convert between formats in this library.
    - [`sparse.COO.from_numpy`][] :
        Convert a Numpy array to [`sparse.COO`][].
    - [`sparse.COO.from_scipy_sparse`][] :
        Convert a SciPy sparse matrix to [`sparse.COO`][].
    - [`sparse.COO.from_iter`][] :
        Convert an iterable to [`sparse.COO`][].
    """
    from .._common import _is_scipy_sparse_obj

    if hasattr(x, "shape") and shape is not None:
        raise ValueError("Cannot provide a shape in combination with something that already has a shape.")

    if hasattr(x, "fill_value") and fill_value is not None:
        raise ValueError("Cannot provide a fill-value in combination with something that already has a fill-value.")

    if isinstance(x, SparseArray):
        return x.asformat("coo")

    if isinstance(x, np.ndarray) or np.isscalar(x):
        return COO.from_numpy(x, fill_value=fill_value, idx_dtype=idx_dtype)

    if _is_scipy_sparse_obj(x):
        return COO.from_scipy_sparse(x)

    if isinstance(x, Iterable | Iterator):
        return COO.from_iter(x, shape=shape, fill_value=fill_value)

    raise NotImplementedError(
        f"Format not supported for conversion. Supplied type is "
        f"{type(x)}, see help(sparse.as_coo) for supported formats."
    )