pandas-dev/pandas · error · TypeError

Invalid value for dtype 'str'. Value should be a string or…

Error message

Invalid value for dtype 'str'. Value should be a string or missing value (or array of those).

What it means

Thrown by StringArray._validate_setitem_value in pandas/core/arrays/string_.py:863 when assigning a NON-SCALAR value (list, ndarray, another array) whose contents include at least one non-string, non-missing element (lib.is_string_array with skipna=True returns False). This is the array-form counterpart of error 457.

Solutions

  1. Stringify the array: string_array[:] = [str(x) for x in values] or np.array([...], dtype=str).
  2. Replace non-string entries with a missing sentinel before assignment.
  3. Assign from another string-dtype Series/array to keep the type chain consistent.

Example fix

// before
s = pd.Series(['a','b','c'], dtype='string')
s[:] = [1, 2, 3]  # raises TypeError

// after
s[:] = [str(x) for x in [1, 2, 3]]
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np, pandas as pd
def safe_setitem_array(arr, key, values):
    if isinstance(getattr(arr, 'dtype', None), pd.StringDtype):
        values = np.asarray(values, dtype=object)
        mask = pd.isna(values)
        values = np.array([str(v) for v in values], dtype=object)
        values[mask] = arr.dtype.na_value
    arr[key] = values

Type guard

import pandas._libs.lib as lib
def all_strings_or_na_array(values) -> bool:
    import numpy as np
    return lib.is_string_array(np.asarray(values, dtype=object), skipna=True)

Try / catch

null

Prevention

When it happens

Trigger: Executing string_array[:] = [1, 2, 3] or string_array[[0,1]] = np.array([0,1]). Assigning a categorical or arrow-backed array whose values are not all strings.

Common situations: Bulk-replacing a string column with values from a numeric column. Assigning a list comprehension that produced ints. Setting a slice from a list with mixed types where pandas does not auto-coerce.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/string_.py:863

                value = self.dtype.na_value
            elif not isinstance(value, str):
                raise TypeError(
                    f"Invalid value '{value}' for dtype '{self.dtype}'. Value should "
                    f"be a string or missing value, got '{type(value).__name__}' "
                    "instead."
                )
        else:
            value = extract_array(value, extract_numpy=True)
            if not is_array_like_deprecate_non_pandas(value):
                value = np.asarray(value, dtype=object)
            elif isinstance(value.dtype, type(self.dtype)):
                return value
            else:
                # cast categories and friends to arrays to see if values are
                # compatible, compatibility with arrow backed strings
                value = np.asarray(value)
            if len(value) and not lib.is_string_array(value, skipna=True):
                raise TypeError(
                    "Invalid value for dtype 'str'. Value should be a "
                    "string or missing value (or array of those)."
                )
        return value

    def __setitem__(self, key, value) -> None:
        if self._readonly:
            raise ValueError("Cannot modify read-only array")

        value = self._validate_setitem_value(value)

        key = check_array_indexer(self, key)
        scalar_key = lib.is_scalar(key)
        scalar_value = lib.is_scalar(value)
        if scalar_key and not scalar_value:
            raise ValueError("setting an array element with a sequence.")

        if not scalar_value:

View on GitHub (pinned to 3b7651241d)