{"record":{"id":"0e136acb57f1ae64","repo":"pandas-dev/pandas","slug":"bins-argument-only-works-with-numeric-data","errorCode":null,"errorMessage":"bins argument only works with numeric data.","messagePattern":"bins argument only works with numeric data\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/algorithms.py","lineNumber":1021,"sourceCode":"        DatetimeIndex,\n        Index,\n        Series,\n        TimedeltaIndex,\n    )\n\n    index_name = getattr(values, \"name\", None)\n    name = \"proportion\" if normalize else \"count\"\n\n    if bins is not None:\n        from pandas.core.reshape.tile import cut\n\n        if isinstance(values, Series):\n            values = values._values\n\n        try:\n            ii = cut(values, bins, include_lowest=True)\n        except TypeError as err:\n            raise TypeError(\"bins argument only works with numeric data.\") from err\n\n        # count, remove nulls (from the index), and but the bins\n        result = ii.value_counts(dropna=dropna)\n        result.name = name\n        result = result[result.index.notna()]\n        result.index = result.index.astype(\"interval\")\n        result = result.sort_index()\n\n        # if we are dropna and we have NO values\n        if dropna and (result._values == 0).all():\n            result = result.iloc[0:0]\n\n        # normalizing is by len of all (regardless of dropna)\n        normalize_denominator = len(ii)\n\n    else:\n        normalize_denominator = None\n        if is_extension_array_dtype(values):","sourceCodeStart":1003,"sourceCodeEnd":1039,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/algorithms.py#L1003-L1039","documentation":"The value_counts() method accepts a bins parameter to group values into equal-width numeric intervals before counting. Internally it delegates to pd.cut(), which requires numeric data to define interval edges. When the underlying values are non-numeric (strings, datetimes that cannot be binned, categorical, etc.), cut() raises a TypeError that is caught and re-raised with this clearer message.","triggerScenarios":"Calling df['category_column'].value_counts(bins=5) on a string or object-dtype column. Calling Series.value_counts(bins=10) on a boolean or timedelta column that cut() cannot bin. Passing bins to value_counts on categorical data.","commonSituations":"Applying a generic value_counts(bins=N) template across mixed-type DataFrame columns without checking dtype first. Processing a column that was expected to be numeric but contains string representations of numbers or mixed types. Reusing analysis code from a numeric pipeline on a text-heavy dataset.","solutions":["Remove the bins parameter for non-numeric columns: df['col'].value_counts().","Convert the column to numeric first: pd.to_numeric(df['col'], errors='coerce').value_counts(bins=5).","Check the dtype before applying bins: if df['col'].dtype.kind in 'iufc': df['col'].value_counts(bins=5) else: df['col'].value_counts()."],"exampleFix":"# before\ndf['category'].value_counts(bins=5)\n\n# after\ndf['category'].value_counts()  # no binning for categorical data","handlingStrategy":"validation","validationCode":"def safe_value_counts(series, bins=None):\n    if bins is not None and series.dtype.kind not in 'iufcb':\n        # integer, unsigned, float, complex, boolean\n        raise TypeError(\n            f\"bins requires numeric data, got dtype {series.dtype}\"\n        )\n    return series.value_counts(bins=bins)","typeGuard":"def is_numeric_for_bins(series) -> bool:\n    return series.dtype.kind in 'iufcb'","tryCatchPattern":"try:\n    result = df['col'].value_counts(bins=5)\nexcept TypeError as e:\n    if \"bins argument\" in str(e):\n        result = df['col'].value_counts()  # fall back without bins\n    else:\n        raise","preventionTips":["Check df['col'].dtype.kind before passing bins to value_counts.","Use df.select_dtypes(include='number') to filter before applying bins-based value_counts.","Build a dtype-aware utility that skips bins for non-numeric columns."],"tags":["pandas","value-counts","bins","dtype","typeerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}