{"record":{"id":"c5a67146cf557c9b","repo":"pandas-dev/pandas","slug":"type-arr-name-has-no-diff-method-convert","errorCode":null,"errorMessage":"{type(arr).__name__} has no 'diff' method. Convert to a suitable dtype prior to calling 'diff'.","messagePattern":"(.+?) has no 'diff' method\\. Convert to a suitable dtype prior to calling 'diff'\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/algorithms.py","lineNumber":1544,"sourceCode":"    is_bool = is_bool_dtype(dtype)\n    if is_bool:\n        op = operator.xor\n    else:\n        op = operator.sub\n\n    if isinstance(dtype, NumpyEADtype):\n        # NumpyExtensionArray cannot necessarily hold shifted versions of itself.\n        arr = arr.to_numpy()\n        dtype = arr.dtype\n\n    if not isinstance(arr, np.ndarray):\n        # i.e ExtensionArray\n        if hasattr(arr, f\"__{op.__name__}__\"):\n            if axis >= arr.ndim:\n                raise ValueError(f\"cannot diff {type(arr).__name__} on axis={axis}\")\n            return op(arr, arr.shift(n))\n        else:\n            raise TypeError(\n                f\"{type(arr).__name__} has no 'diff' method. \"\n                \"Convert to a suitable dtype prior to calling 'diff'.\"\n            )\n\n    is_timedelta = False\n    if arr.dtype.kind in \"mM\":\n        dtype = np.int64\n        arr = arr.view(\"i8\")\n        na = iNaT\n        is_timedelta = True\n\n    elif is_bool:\n        # We have to cast in order to be able to hold np.nan\n        dtype = np.object_\n\n    elif dtype.kind in \"iu\":\n        # We have to cast in order to be able to hold np.nan\n","sourceCodeStart":1526,"sourceCodeEnd":1562,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/algorithms.py#L1526-L1562","documentation":"When diff() is called on an ExtensionArray that does not implement the subtraction (__sub__ or __xor__) operator, pandas cannot compute element-wise differences. ExtensionArrays like CategoricalArray, IntervalArray (in some contexts), or custom third-party arrays may lack arithmetic support. The error message directs the user to convert the data to a suitable dtype before calling diff.","triggerScenarios":"Calling df['categorical_col'].diff() where the column is dtype 'category'. Calling diff on an IntervalArray or a custom ExtensionArray that has no __sub__ method. Attempting to diff string/object data backed by an ExtensionArray.","commonSituations":"Loading data with pd.read_csv(dtype={'col': 'category'}) and then trying to diff that column. Using Arrow-backed string arrays (dtype 'string[pyarrow]') and calling diff(). Building analysis pipelines that assume all columns are numeric.","solutions":["Convert to numeric before diffing: df['col'].astype('float64').diff().","If the column is categorical with numeric categories, use df['col'].cat.codes.diff() to diff the integer codes.","Check the dtype: if df['col'].dtype.name == 'category': convert or skip diff for that column."],"exampleFix":"# before\ndf['category_col'].diff()\n\n# after — convert category codes to integers first\ndf['category_col'].cat.codes.diff()","handlingStrategy":"type-guard","validationCode":"def safe_diff(series, n=1):\n    if hasattr(series._values, '__sub__') or series.dtype.kind in 'iufcmM':\n        return series.diff(n)\n    else:\n        raise TypeError(f\"Cannot diff dtype {series.dtype}; convert to numeric first\")","typeGuard":"def is_diffable_dtype(dtype) -> bool:\n    return dtype.kind in 'iufcmMb' or hasattr(dtype, '__sub__')","tryCatchPattern":"try:\n    result = df['col'].diff()\nexcept TypeError as e:\n    if \"no 'diff' method\" in str(e):\n        result = df['col'].astype('float64').diff()\n    else:\n        raise","preventionTips":["Check df['col'].dtype.kind before calling diff — only numeric and datetime dtypes are supported.","Convert categorical columns to codes or numeric before diffing.","Use df.select_dtypes(include='number').diff() for mixed-type DataFrames."],"tags":["pandas","diff","extension-array","categorical","dtype","typeerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}