Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas groupby() Method



The Pandasgroupby() method in Python is a powerful tool for data aggregation and analysis. It splits the data into groups, applies a function to each group, and combines the results. This method is essential for data analysis tasks like aggregation, transformations and filtration.

The Pandasgroupby() method can be used on both PandasSeries andDataFrame objects, including those with hierarchical indexes. This method is designed to −

  • Split data into groups based on specified criteria.

  • Apply a function to each group independently.

  • Combine the results into a structured format.

Syntax

Following is the syntax of the Python Pandas groupby() method

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

Parameters

The Python Pandas groupby() method accepts the below parameters −

  • by: Used to define how to group data. It can be a function, label, Series, or list of labels.

  • axis: Determines grouping by rows (0) or columns (1).

  • level: Groups by specific levels of a MultiIndex.

  • as_index: If True, group labels are used as the index in the result. If False, returns the result with the original index.

  • sort: Sort group keys (default is True).

  • group_keys: Adds group keys to the index when applying functions. OR Adds group keys to the result if True.

  • observed: If True, shows only observed categories when grouping the categorical data.

  • dropna: If True, excludes NA values from group keys.

Return Value

The Pandasgroupby() method returns a special object depending on the input type. This object is eitherpandas.api.typing.DataFrameGroupBy orpandas.api.typing.SeriesGroupBy, representing grouped data for further operations.

Example: Grouping a Series by Index Labels

This example demonstrates the basic functionality of theSeries.groupby() method by grouping a Pandas Series using index labels.

import pandas as pds = pd.Series([1000, 1400, 1000, 900, 1700], index=['BMW', 'Audi', 'Mercedes', 'Audi', 'BMW'], name='Car')# Display the Input Seriesprint("Original Series:")print(s)# Grouping the Series by Index Labelsresult = s.groupby(level=0).sum()print("\nSeries after Grouping:")print(result)

When we run above program, it produces following result −

Original Series:BMW         1000Audi        1400Mercedes    1000Audi         900BMW         1700Name: Car, dtype: int64Series after Grouping:Audi        2300BMW         2700Mercedes    1000Name: Car, dtype: int64

Example: Grouping a DataFrame Column

The following example demonstrates using the Pandasgroupby() method for grouping the DataFrame column.

import pandas as pd# Create a DataFrame df = pd.DataFrame({'Car':['BMW', 'Audi', 'Mercedes', 'Audi', 'BMW'], 'Price':[1000, 1400, 1000, 900, 1700]})# Display the Input DataFrameprint("Input DataFrame:")print(df)# Grouping a DataFrame Columnresult = df.groupby("Car").mean()print("\nDataFrame after Grouping Based on a Column:")print(result)

While executing the above code we get the following output −

Input DataFrame:
CarPrice
0BMW1000
1Audi1400
2Mercedes1000
3Audi900
4BMW1700
DataFrame after Grouping Based on a Column:
Price
Car
Audi1150.0
BMW1350.0
Mercedes1000.0

Example: Grouping while Handling Missing Values

Handling missing values is a easy task while grouping the Pandas objects using thedropna parameter. The following example sets thedropna=False for including NA values as a separate group.

import pandas as pdimport numpy as np# Create a DataFrame df = pd.DataFrame({'Car':['BMW', 'Audi', np.nan, 'Audi', 'BMW'], 'Price':[1000, 1400, 1000, 900, 1700]})# Display the Input DataFrameprint("Input DataFrame:")print(df)# Including NA as a separate groupresult = df.groupby("Car", dropna=False).sum()print("\nDataFrame after Grouping:")print(result)

Following is an output of the above code −

Input DataFrame:
CarPrice
0BMW1000
1Audi1400
2NaN1000
3Audi900
4BMW1700
DataFrame after Grouping:
Price
Car
Audi2300
BMW2700
Nan1000

Example: Grouping by Multiple Columns

This example demonstrates grouping a Pandas DataFrame by multiple columns.

import pandas as pdimport numpy as np# Create a DataFrame df = pd.DataFrame({'Car':['BMW', 'Audi', np.nan, 'Audi', 'BMW'], 'Price':[1000, 1400, 1000, 900, 1700],'color': ['white', 'black', 'red', 'red', 'white']})# Display the Input DataFrameprint("Input DataFrame:")print(df)# Grouping a DataFrame by multiple columns result = df.groupby(["Car", "color"], dropna=False).sum()print("\nDataFrame after Grouping Based on Multiple Column:")print(result)

When we run above program, it produces following result −

Input DataFrame:
CarPricecolor
0BMW1000white
1Audi1400black
2NaN1000red
3Audi900red
4BMW1700white
DataFrame after Grouping Based on Multiple Column:
Price
Carcolor
Audiblack1400
red900
BMWwhite2700
NaNred1000

Example: Grouping with Hierarchical Indexes

Grouping of a hierarchical index can be done by using thelevel parameter of thegroupby() method. following example demonstrates the same.

import pandas as pdimport numpy as np# Create a DataFrame data = [['BMW', 'BMW', 'Audi', 'Audi'], ['white', 'black', 'black', 'white']]# Create a MultiIndex objectindex = pd.MultiIndex.from_arrays(data, names=("car", "color"))# Creating a MultiIndexed Seriesdf = pd.DataFrame({'Price': [1000, 1400, 1000, 900]}, index=index)# Display the input MultiIndexed DataFrameprint("Input MultiIndexed DataFrame:\n")print(df)# Grouping MultiIndexed by level nameresult = df.groupby("car").sum()print("\nMultiIndexed DataFrame after Grouping:")print(result)

Following is an output of the above code −

Input MultiIndexed DataFrame:
Price
carcolor
BMWwhite1000
black1400
Audiblack1000
white900
MultiIndexed DataFrame after Grouping:
Price
car
Audi1900
BMW2400
python_pandas_groupby.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp