pandas-dev/pandas · error · ValueError

axis is out of bounds for array of dimension

Error message

axis {axis} is out of bounds for array of dimension {first.ndim}

What it means

Raised in Categorical._concat_same_type when the axis argument is greater than or equal to the number of dimensions of the categorical arrays being concatenated. A 1-D categorical only has axis 0; passing axis=1 is out of bounds. The guard exists because concat dispatch may pass an axis meant for 2-D ExtensionArray stacking.

Solutions

  1. Confirm the intended axis: 1-D categoricals concatenate along axis=0.
  2. Use pd.concat([s1, s2], axis=1) at the Series level rather than calling EA concat directly.
  3. Ensure inputs are 2-D if you genuinely need axis=1 (e.g., stack into a 2-D array first).
  4. Check that to_concat elements are not accidentally squeezed to 1-D before the call.

Example fix

# before (illustrative of the internal guard)
c1 = pd.Categorical(['a','b'])
c2 = pd.Categorical(['c','d'])
pd.Categorical._concat_same_type([c1, c2], axis=1)  # ValueError

# after
pd.Categorical._concat_same_type([c1, c2], axis=0)
Defensive patterns

Strategy: validation

Validate before calling

if axis >= to_concat[0].ndim:
    raise ValueError(f'axis {axis} out of range for {to_concat[0].ndim}-D arrays')
result = pd.Categorical._concat_same_type(to_concat, axis=axis)

Type guard

def valid_axis_for_concat(axis: int, arrays) -> bool:
    return 0 <= axis < min(a.ndim for a in arrays)

Try / catch

try:
    out = pd.Categorical._concat_same_type(parts, axis=axis)
except ValueError as e:
    if 'out of bounds' in str(e):
        out = pd.Categorical._concat_same_type(parts, axis=0)
    else:
        raise

Prevention

When it happens

Trigger: pd.concat([cat1, cat2], axis=1) routing through _concat_same_type on 1-D categoricals. Internal 2-D reshape path where the input was unexpectedly 1-D. Calling Categorical._concat_same_type directly with axis>=ndim.

Common situations: Concatenating Series along axis=1 to form a DataFrame where the block consolidation path hits categorical concatenation with the wrong axis. Building a DataFrame column-by-column with categoricals under a code path that forwards axis=1 to the EA-level concat.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/de7be14cd65ac312. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/categorical.py:2692

        codes = self.codes.copy()
        mask = self.isna()
        if func == np.minimum.accumulate:
            codes[mask] = np.iinfo(codes.dtype.type).max
        # no need to change codes for maximum because codes[mask] is already -1
        if not skipna:
            mask = np.maximum.accumulate(mask)

        codes = func(codes)
        codes[mask] = -1
        return self._simple_new(codes, dtype=self._dtype)

    @classmethod
    def _concat_same_type(cls, to_concat: Sequence[Self], axis: AxisInt = 0) -> Self:
        from pandas.core.dtypes.concat import union_categoricals

        first = to_concat[0]
        if axis >= first.ndim:
            raise ValueError(
                f"axis {axis} is out of bounds for array of dimension {first.ndim}"
            )

        if axis == 1:
            # Flatten, concatenate then reshape
            if not all(x.ndim == 2 for x in to_concat):
                raise ValueError

            # pass correctly-shaped to union_categoricals
            tc_flat = []
            for obj in to_concat:
                tc_flat.extend([obj[:, i] for i in range(obj.shape[1])])

            res_flat = cls._concat_same_type(tc_flat, axis=0)

            result = res_flat.reshape(len(first), -1, order="F")
            return result

View on GitHub (pinned to 3b7651241d)