Skip to main content
`Ctrl`+`K`

# pandas.NamedAgg

class pandas.NamedAgg(column, aggfunc, *args, **kwargs)

  Helper for column specific aggregation with control over output column names.

  A dataclass used with `DataFrame.groupby().agg()` to specify an aggregation on a particular column and assign a custom name to the resulting column. Additional positional and keyword arguments can be forwarded to the aggregation function.

  Parameters:
    column Hashable

      Column label in the DataFrame to apply aggfunc.

    aggfunc function or str

      Function to apply to the provided column. If string, the name of a built-in pandas function.

    *args, **kwargs Any

      Optional positional and keyword arguments passed to `aggfunc`.

  See also

  `DataFrame.groupby`

    Group DataFrame using a mapper or by a Series of columns.

  Examples

      >>> df = pd.DataFrame({"key": [1, 1, 2], "a": [-1, 0, 1], 1: [10, 11, 12]})
      >>> agg_a = pd.NamedAgg(column="a", aggfunc="min")
      >>> agg_1 = pd.NamedAgg(column=1, aggfunc=lambda x: np.mean(x))
      >>> df.groupby("key").agg(result_a=agg_a, result_1=agg_1)
          result_a  result_1
      key
      1          -1      10.5
      2           1      12.0

      >>> def n_between(ser, low, high, **kwargs):
      ...     return ser.between(low, high, **kwargs).sum()

      >>> agg_between = pd.NamedAgg("a", n_between, 0, 1)
      >>> df.groupby("key").agg(count_between=agg_between)
          count_between
      key
      1               1
      2               1

      >>> agg_between_kw = pd.NamedAgg("a", n_between, 0, 1, inclusive="both")
      >>> df.groupby("key").agg(count_between_kw=agg_between_kw)
          count_between_kw
      key
      1                   1
      2                   1

  Attributes

  `args` |

  Methods