{"record":{"id":"a0eff1096f884352","repo":"pandas-dev/pandas","slug":"numpy-operations-are-not-valid-with-groupby-use","errorCode":null,"errorMessage":"numpy operations are not valid with groupby. Use .groupby(...).{name}() instead","messagePattern":"numpy operations are not valid with groupby\\. Use \\.groupby\\(\\.\\.\\.\\)\\.(.+?)\\(\\) instead","errorType":"exception","errorClass":"UnsupportedFunctionCall","httpStatus":null,"severity":"error","filePath":"pandas/compat/numpy/function.py","lineNumber":340,"sourceCode":"\ndef validate_groupby_func(\n    name: str,\n    args: tuple[Any, ...],\n    kwargs: dict[str, Any],\n    allowed: list[str] | None = None,\n) -> None:\n    \"\"\"\n    'args' and 'kwargs' should be empty, except for allowed kwargs because all\n    of their necessary parameters are explicitly listed in the function\n    signature\n    \"\"\"\n    if allowed is None:\n        allowed = []\n\n    extra_kwargs = set(kwargs) - set(allowed)\n\n    if len(args) + len(extra_kwargs) > 0:\n        raise UnsupportedFunctionCall(\n            \"numpy operations are not valid with groupby. \"\n            f\"Use .groupby(...).{name}() instead\"\n        )\n\n\ndef validate_minmax_axis(axis: AxisInt | None, ndim: int = 1) -> None:\n    \"\"\"\n    Ensure that the axis argument passed to min, max, argmin, or argmax is zero\n    or None, as otherwise it will be incorrectly ignored.\n\n    Parameters\n    ----------\n    axis : int or None\n    ndim : int, default 1\n\n    Raises\n    ------\n    ValueError","sourceCodeStart":322,"sourceCodeEnd":358,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/compat/numpy/function.py#L322-L358","documentation":"Raised by validate_groupby_func (compat/numpy/function.py:323-343) as UnsupportedFunctionCall when a groupby aggregation method (sum, prod, mean, median, min, max, etc.) receives positional args or unrecognized keyword args that mimic numpy's ndarray method signatures (dtype, out, keepdims, axis-as-positional, etc.). pandas groupby aggs expose their own signatures and reject numpy-style passthrough kwargs to prevent silent wrong results.","triggerScenarios":"df.groupby('key').sum(skipna=False, min_count=1) with an arg not in the allowed list; df.groupby('key').prod(dtype='float64'); df.groupby('key').mean(0) (passing axis positionally). Each method has an allowed-kwarg list (SUM_DEFAULTS, STAT_FUNC_DEFAULTS, etc.); anything outside it triggers validate_groupby_func.","commonSituations":"Copy-pasting a numpy call pattern (np.sum(a, axis=0, dtype=...)) onto a groupby object; assuming groupby.sum accepts the same kwargs as ndarray.sum; passing axis positionally to mean/median; passing keepdims which is numpy-only.","solutions":["Use only the documented groupby kwargs: min_count (sum/prod), numeric_only (many), skipna where supported.","Remove numpy-specific kwargs: dtype, out, keepdims, keepdims=, and axis-as-positional-arg.","For dtype control, cast beforehand: df['c'] = df['c'].astype('float64') then groupby.sum().","For axis, groupby already operates along the grouped axis — do not pass axis."],"exampleFix":"# before\ndf.groupby('key')['v'].sum(dtype='float64', min_count=1)\n\n# after\ndf['v'] = df['v'].astype('float64')\ndf.groupby('key')['v'].sum(min_count=1)","handlingStrategy":"validation","validationCode":"ALLOWED_SUM = {'min_count', 'numeric_only', 'skipna'}\nkwargs = {'min_count': 1}\nbad = set(kwargs) - ALLOWED_SUM\nif bad:\n    raise TypeError(f'unsupported groupby kwargs: {bad}')\ndf.groupby('key')['v'].sum(**kwargs)","typeGuard":null,"tryCatchPattern":"try:\n    df.groupby('key')['v'].sum(**kwargs)\nexcept Exception as e:\n    if 'numpy operations are not valid with groupby' in str(e):\n        # strip numpy-only kwargs (dtype, out, keepdims, axis) and retry\n        clean = {k: v for k, v in kwargs.items() if k not in {'dtype','out','keepdims','axis'}}\n        df.groupby('key')['v'].sum(**clean)\n    else:\n        raise","preventionTips":["Consult the groupby method's signature for supported kwargs before passing any.","Never forward numpy ndarray kwargs (dtype/out/keepdims) to groupby aggs.","Cast dtypes and handle axes before the groupby, not inside the aggregation."],"tags":["groupby","numpy","unsupported-function-call","aggregation","kwargs"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}