w3resource

Pandas DataFrame: groupby() function

DataFrame - groupby() function

The groupby() function is used to group DataFrame or Series using a mapper or by a Series of columns.

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

Syntax:

DataFrame.groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)

Parameters:

Name Description Type/Default Value Required / Optional
by Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key. mapping, function, label, or list of labels Required
axis  Split along rows (0) or columns (1). {0 or ‘index’, 1 or ‘columns’}
Default Value: 0
Required
level  If the axis is a MultiIndex (hierarchical), group by a particular level or levels. int, level name, or sequence of such,
Default Value: None
Required
as_index  For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output. bool
Default Value: True
Required
sort  Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group. bool
Default Value: True
Required
group_keys  When calling apply, add group keys to index to identify pieces. bool
Default Value: True
Required
squeeze  Reduce the dimensionality of the return type if possible, otherwise return a consistent type. bool
Default Value: False
Required
observed  This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. bool
Default Value: False
Required
**kwargs Optional, only accepts keyword argument 'mutated' and is passed to groupby.   Optional

Returns: DataFrameGroupBy or SeriesGroupBy
Depends on the calling object and returns groupby object that contains information about the groups.

Example:


Download the Pandas DataFrame Notebooks from here.

Previous: DataFrame - transform() function
Next: DataFrame - rolling() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/pandas/dataframe/dataframe-groupby.php