Skip to content

expand_dims

Expands the shape of an array by inserting a new axis (dimension) of size one at the position specified by axis.

Parameters:

Name Type Description Default
a COO

Input COO array.

required
axis int

Position in the expanded axes where the new axis is placed.

0

Returns:

Name Type Description
result COO

An expanded output COO array having the same data type as x.

Examples:

>>> import sparse
>>> x = sparse.COO.from_numpy([[1, 0, 0, 0, 2, -3]])
>>> x.shape
(1, 6)
>>> y1 = sparse.expand_dims(x, axis=1)
>>> y1.shape
(1, 1, 6)
>>> y2 = sparse.expand_dims(x, axis=2)
>>> y2.shape
(1, 6, 1)
Source code in sparse/numba_backend/_coo/common.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
def expand_dims(x, /, *, axis=0):
    """
    Expands the shape of an array by inserting a new axis (dimension) of size
    one at the position specified by ``axis``.

    Parameters
    ----------
    a : COO
        Input COO array.
    axis : int
        Position in the expanded axes where the new axis is placed.

    Returns
    -------
    result : COO
        An expanded output COO array having the same data type as ``x``.

    Examples
    --------
    >>> import sparse
    >>> x = sparse.COO.from_numpy([[1, 0, 0, 0, 2, -3]])
    >>> x.shape
    (1, 6)
    >>> y1 = sparse.expand_dims(x, axis=1)
    >>> y1.shape
    (1, 1, 6)
    >>> y2 = sparse.expand_dims(x, axis=2)
    >>> y2.shape
    (1, 6, 1)

    """

    x = _validate_coo_input(x)

    if not isinstance(axis, int):
        raise IndexError(f"Invalid axis position: {axis}")

    axis = normalize_axis(axis, x.ndim + 1)

    new_coords = np.insert(x.coords, obj=axis, values=np.zeros(x.nnz, dtype=np.intp), axis=0)
    new_shape = list(x.shape)
    new_shape.insert(axis, 1)
    new_shape = tuple(new_shape)

    from .core import COO

    return COO(
        new_coords,
        x.data,
        shape=new_shape,
        fill_value=x.fill_value,
    )