pola-rs/polars · error
only 1D NumPy arrays can be treated as indices
Error message
only 1D NumPy arrays can be treated as indices
What it means
`_convert_np_ndarray_to_indices` only accepts 1-D NumPy arrays as row index selectors. After promoting 0-D arrays via `np.atleast_1d`, any array with ndim != 1 (2-D matrix, etc.) raises TypeError because a multi-dimensional array has no single positional meaning per row.
Solutions
- Flatten with `.ravel()` or select one column before indexing: `s[arr.ravel()]`.
- If you meant multiple independent index vectors, loop or use `np.concatenate`.
- Verify `arr.ndim == 1` before indexing.
Example fix
// before arr = np.array([[0, 1], [2, 3]]) sub = s[arr] # TypeError: only 1D NumPy arrays... // after sub = s[arr.ravel()]
Defensive patterns
Strategy: type-guard
Validate before calling
import numpy as np
if isinstance(idx, np.ndarray) and idx.ndim != 1:
idx = idx.ravel() Type guard
def is_1d_int_array(x) -> bool:
return isinstance(x, np.ndarray) and x.ndim == 1 and x.dtype.kind in ('i', 'u') Try / catch
try:
sub = s[np_idx]
except TypeError as e:
if "only 1D NumPy arrays" in str(e):
sub = s[np.asarray(np_idx).ravel()]
else:
raise Prevention
- Check `arr.ndim == 1` before using arrays as indices.
- Beware broadcasting/`np.newaxis` adding dims to index arrays.
- Never pass `df.to_numpy()` output directly as an index.
When it happens
Trigger: Passing a 2-D NumPy array to `s[np_arr]` or `df[np_arr]`, e.g. `s[np.array([[0, 1], [2, 3]])]` or the result of a vectorized computation that added a dimension.
Common situations: NumPy broadcasting/expanding an index array (`np.newaxis`, stacking, `np.meshgrid` output), or passing `df.to_numpy()` output back as an index.
Related errors
- cannot treat NumPy array of type
- cannot treat Series of type
- expected data of type Sequence, got
- expected type 'int | str', got
- arr.dot query vector must be one-dimensional
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/2ef99fea64b49370.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/_utils/getitem.py:412
return s.cast(idx_type)
def _convert_np_ndarray_to_indices(arr: np.ndarray[Any, Any], size: int) -> Series:
"""Convert a NumPy ndarray to indices, taking into account negative values."""
# Unsigned or signed Numpy array (ordered from fastest to slowest).
# - np.uint32 (polars) or np.uint64 (polars_u64_idx) numpy array
# indexes.
# - Other unsigned numpy array indexes are converted to pl.UInt32
# (polars) or pl.UInt64 (polars_u64_idx).
# - Signed numpy array indexes are converted pl.UInt32 (polars) or
# pl.UInt64 (polars_u64_idx) after negative indexes are converted
# to absolute indexes.
if arr.ndim == 0:
arr = np.atleast_1d(arr)
if arr.ndim != 1:
msg = "only 1D NumPy arrays can be treated as indices"
raise TypeError(msg)
idx_type = get_index_type()
if len(arr) == 0:
return pl.Series("", [], dtype=idx_type)
# Numpy array with signed or unsigned integers.
if arr.dtype.kind not in ("i", "u"):
if arr.dtype.kind == "b":
_raise_on_boolean_mask()
else:
msg = f"cannot treat NumPy array of type {arr.dtype} as indices"
raise TypeError(msg)
if idx_type == UInt32:
if arr.dtype in {np.int64, np.uint64} and arr.max() >= U32_MAX:
msg = "index positions should be smaller than 2^32"
raise ValueError(msg)View on GitHub (pinned to fe841f959e)