{"record":{"id":"0f0a1feff77dee64","repo":"numpy/numpy","slug":"can-only-create-a-chararray-from-string-data","errorCode":null,"errorMessage":"Can only create a chararray from string data.","messagePattern":"Can only create a chararray from string data\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"numpy/_core/defchararray.py","lineNumber":593,"sourceCode":"                                   offset=offset, strides=strides,\n                                   order=order)\n        if filler is not None:\n            self[...] = filler\n\n        return self\n\n    def __array_wrap__(self, arr, context=None, return_scalar=False):\n        # When calling a ufunc (and some other functions), we return a\n        # chararray if the ufunc output is a string-like array,\n        # or an ndarray otherwise\n        if arr.dtype.char in \"SUbc\":\n            return arr.view(type(self))\n        return arr\n\n    def __array_finalize__(self, obj):\n        # The b is a special case because it is used for reconstructing.\n        if self.dtype.char not in 'VSUbc':\n            raise ValueError(\"Can only create a chararray from string data.\")\n\n    def __getitem__(self, obj):\n        val = ndarray.__getitem__(self, obj)\n        if isinstance(val, character):\n            return val.rstrip()\n        return val\n\n    # IMPLEMENTATION NOTE: Most of the methods of this class are\n    # direct delegations to the free functions in this module.\n    # However, those that return an array of strings should instead\n    # return a chararray, so some extra wrapping is required.\n\n    def __eq__(self, other):\n        \"\"\"\n        Return (self == other) element-wise.\n\n        See Also\n        --------","sourceCodeStart":575,"sourceCodeEnd":611,"githubUrl":"https://github.com/numpy/numpy/blob/e117b3ca4edacf581f440dccfd7f3242f0312afa/numpy/_core/defchararray.py#L575-L611","documentation":"Raised in chararray.__array_finalize__ when the array's dtype kind is not one of V/S/U/b/c (void, bytes, unicode, bytes-native, character). chararray is a string-only subclass; numpy refuses to finalize it over numeric or object data. Guard at defchararray.py:592.","triggerScenarios":"Viewing or slicing a non-string ndarray as a chararray (e.g. arr.view(np.char.chararray) on an int/float array), or constructing/reshaping that triggers __array_finalize__ with a non-string dtype.","commonSituations":"Migrating legacy np.char usage onto numeric arrays; using .astype after .view in the wrong order; copy/slicing operations that propagate a chararray type onto data of a different dtype.","solutions":["Convert the data to a string dtype first, then view as chararray: arr.astype('U').view(np.char.chararray).","Use np.char.asarray(arr) which handles dtype conversion explicitly instead of bare .view.","Drop the chararray subclass and operate on a plain ndarray of str_/bytes_ dtype, which is the modern recommendation."],"exampleFix":"// before\nnp.array([1, 2, 3]).view(np.char.chararray)\n// after\nnp.array([1, 2, 3]).astype('U').view(np.char.chararray)","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef to_chararray(arr):\n    a = np.asarray(arr)\n    if a.dtype.char not in 'VSUbc':\n        a = a.astype('U')\n    return a.view(np.char.chararray)","typeGuard":"def is_string_dtype(arr) -> bool:\n    return np.asarray(arr).dtype.char in 'VSUbc'","tryCatchPattern":null,"preventionTips":["Convert to a string dtype before calling .view(np.char.chararray).","Prefer np.char.asarray or plain str_/bytes_ ndarrays over manual chararray views.","Avoid subclassing/viewing chararray for numeric data; chararray is legacy and string-only."],"tags":["numpy","chararray","dtype","view","argument-validation"],"analyzedSha":"e117b3ca4edacf581f440dccfd7f3242f0312afa","analyzedAt":"2026-08-07T01:25:31.049Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}