Skip to content

select

select(
    src: Union[array, list, tuple],
    index_or_mask: Union[array, list],
    axis: int = 0,
) -> Union[array, list]

Selects the entries of src along axis given by an index array or by a boolean mask.

Parameters:

Name Type Description Default
src Union[array, list, tuple]

An array, or a list/tuple (selected along its only axis).

required
index_or_mask Union[array, list]

Indices of the entries to select, or a boolean mask of shape [src.shape[axis]].

required
axis int

The axis along which to select (must be 0 for lists). Default: 0

0

Returns:

Type Description
Union[array, list]

The selected entries, as an array if src is an array and as a list

Union[array, list]

otherwise.

Example:

src = mx.array([[1, 2], [3, 4], [5, 6]])
select(src, mx.array([True, False, True]))
# mx.array([[1, 2], [5, 6]])
select(["a", "b", "c"], mx.array([2, 0]))
# ["c", "a"]
Source code in mlx_graphs/utils/indexing.py
def select(
    src: Union[mx.array, list, tuple],
    index_or_mask: Union[mx.array, list],
    axis: int = 0,
) -> Union[mx.array, list]:
    """
    Selects the entries of ``src`` along ``axis`` given by an index array or
    by a boolean mask.

    Args:
        src: An array, or a list/tuple (selected along its only axis).
        index_or_mask: Indices of the entries to select, or a boolean mask of
            shape ``[src.shape[axis]]``.
        axis: The axis along which to select (must be ``0`` for lists).
            Default: ``0``

    Returns:
        The selected entries, as an array if ``src`` is an array and as a list
        otherwise.

    Example:

    .. code-block:: python

        src = mx.array([[1, 2], [3, 4], [5, 6]])
        select(src, mx.array([True, False, True]))
        # mx.array([[1, 2], [5, 6]])
        select(["a", "b", "c"], mx.array([2, 0]))
        # ["c", "a"]
    """
    index = np.asarray(index_or_mask)
    if index.dtype == np.bool_:
        index = np.nonzero(index)[0]
    index = index.reshape(-1).astype(np.int64)

    if isinstance(src, mx.array):
        if index.size == 0:
            shape = list(src.shape)
            shape[axis] = 0
            return mx.zeros(shape, dtype=src.dtype)
        return mx.take(src, mx.array(index), axis=axis)
    if isinstance(src, (list, tuple)):
        if axis != 0:
            raise ValueError("Cannot select along an axis other than 0 of a list")
        return [src[i] for i in index.tolist()]
    raise ValueError(f"Invalid input type (got '{type(src)}')")

from mlx_graphs.utils import select · mlx_graphs/utils/indexing.py