Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

pandas.Series.groupby#

Series.groupby(by=None,axis=0,level=None,as_index=True,sort=True,group_keys=True,observed=<no_default>,dropna=True)[source]#

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

A groupby operation involves some combination of splitting theobject, applying a function, and combining the results. This can beused to group large amounts of data and compute operations on thesegroups.

Parameters:
bymapping, function, label, pd.Grouper or list of such

Used to determine the groups for the groupby.Ifby is a function, it’s called on each value of the object’sindex. If a dict or Series is passed, the Series or dict VALUESwill be used to determine the groups (the Series’ values are firstaligned; see.align() method). If a list or ndarray of lengthequal to the selected axis is passed (see thegroupby user guide),the values are used as-is to determine the groups. A label or listof labels may be passed to group by the columns inself.Notice that a tuple is interpreted as a (single) key.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Split along rows (0) or columns (1). ForSeries this parameteris unused and defaults to 0.

Deprecated since version 2.1.0:Will be removed and behave like axis=0 in a future version.Foraxis=1, doframe.T.groupby(...) instead.

levelint, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particularlevel or levels. Do not specify bothby andlevel.

as_indexbool, default True

Return object with group labels as theindex. Only relevant for DataFrame input. as_index=False iseffectively “SQL-style” grouped output. This argument has no effecton filtrations (see thefiltrations in the user guide),such ashead(),tail(),nth() and in transformations(see thetransformations in the user guide).

sortbool, default True

Sort group keys. Get better performance by turning this off.Note this does not influence the order of observations within eachgroup. Groupby preserves the order of rows within each group. If False,the groups will appear in the same order as they did in the original DataFrame.This argument has no effect on filtrations (see thefiltrations in the user guide),such ashead(),tail(),nth() and in transformations(see thetransformations in the user guide).

Changed in version 2.0.0:Specifyingsort=False with an ordered categorical grouper will nolonger sort the values.

group_keysbool, default True

When calling apply and theby argument produces a like-indexed(i.e.a transform) result, add group keys toindex to identify pieces. By default group keys are not includedwhen the result’s index (and column) labels match the inputs, andare included otherwise.

Changed in version 1.5.0:Warns thatgroup_keys will no longer be ignored when theresult fromapply is a like-indexed Series or DataFrame.Specifygroup_keys explicitly to include the group keys ornot.

Changed in version 2.0.0:group_keys now defaults toTrue.

observedbool, default False

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.

Deprecated since version 2.1.0:The default value will change to True in a future version of pandas.

dropnabool, default True

If True, and if group keys contain NA values, NA values togetherwith row/column will be dropped.If False, NA values will also be treated as the key in groups.

Returns:
pandas.api.typing.SeriesGroupBy

Returns a groupby object that contains information about the groups.

See also

resample

Convenience method for frequency conversion and resampling of time series.

Notes

See theuser guide for moredetailed usage and examples, including splitting an object into groups,iterating through groups, selecting a group, aggregation, and more.

Examples

>>>ser=pd.Series([390.,350.,30.,20.],...index=['Falcon','Falcon','Parrot','Parrot'],...name="Max Speed")>>>serFalcon    390.0Falcon    350.0Parrot     30.0Parrot     20.0Name: Max Speed, dtype: float64>>>ser.groupby(["a","b","a","b"]).mean()a    210.0b    185.0Name: Max Speed, dtype: float64>>>ser.groupby(level=0).mean()Falcon    370.0Parrot     25.0Name: Max Speed, dtype: float64>>>ser.groupby(ser>100).mean()Max SpeedFalse     25.0True     370.0Name: Max Speed, dtype: float64

Grouping by Indexes

We can groupby different levels of a hierarchical indexusing thelevel parameter:

>>>arrays=[['Falcon','Falcon','Parrot','Parrot'],...['Captive','Wild','Captive','Wild']]>>>index=pd.MultiIndex.from_arrays(arrays,names=('Animal','Type'))>>>ser=pd.Series([390.,350.,30.,20.],index=index,name="Max Speed")>>>serAnimal  TypeFalcon  Captive    390.0        Wild       350.0Parrot  Captive     30.0        Wild        20.0Name: Max Speed, dtype: float64>>>ser.groupby(level=0).mean()AnimalFalcon    370.0Parrot     25.0Name: Max Speed, dtype: float64>>>ser.groupby(level="Type").mean()TypeCaptive    210.0Wild       185.0Name: Max Speed, dtype: float64

We can also choose to includeNA in group keys or not by definingdropna parameter, the default setting isTrue.

>>>ser=pd.Series([1,2,3,3],index=["a",'a','b',np.nan])>>>ser.groupby(level=0).sum()a    3b    3dtype: int64
>>>ser.groupby(level=0,dropna=False).sum()a    3b    3NaN  3dtype: int64
>>>arrays=['Falcon','Falcon','Parrot','Parrot']>>>ser=pd.Series([390.,350.,30.,20.],index=arrays,name="Max Speed")>>>ser.groupby(["a","b","a",np.nan]).mean()a    210.0b    350.0Name: Max Speed, dtype: float64
>>>ser.groupby(["a","b","a",np.nan],dropna=False).mean()a    210.0b    350.0NaN   20.0Name: Max Speed, dtype: float64

[8]ページ先頭

©2009-2025 Movatter.jp