Change language

Python | Pandas dataframe.groupby ()

The Pandas function dataframe.groupby() is used to divide data into groups based on some criteria. Pandas objects can be subdivided into any of their axes. An abstract definition of grouping is to ensure that labels are mapped to group names.

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

Parameters:
by: mapping , function, str, or iterable
axis: int, default 0
level: If the axis is a MultiIndex (hierarchical), group by a particular level or levels
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
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.
group_keys: When calling apply, add group keys to index to identify pieces
squeeze: Reduce the dimensionality of the return type if possible, otherwise return a consistent type

Returns: GroupBy object

To reference the CSV file used in the code, click here

Example # 1: Use groupby () to group data based on Team.

# import pandas as pd

import pandas as pd

 
# Create data frame

df  = pd.read_csv ( "nba.csv" )

 
# Print the data frame
df

Now apply groupby () .

# apply the groupby () function to
# group data by command value.

gk = df.groupby ( ’Team’ )

  
# Let’s print the first posts
# in all generated groups.
gk.first ()

Output:

Let’s print the value contained in any of the group. To do this, use the command name. We use the get_group () function to find records contained in any of the groups.

# Find the values ​​contained in the Boston group Celtics "

gk.get_group ( ’ Boston Celtics’ )

Output:

Example # 2: Use groupby ( ) to form groups based on more than one category (i.e. use more than one column to perform the split).

# pandas import as pd

import pandas as p d

 
# Create data frame

df = pd.read_csv ( " nba.csv " )

  
# First grouping by "Team"
# Within each team we group by "Position"

gkk = daf.groupby ([ ’ Team’ , ’Position’ ])

 
# Display the first value in each group
gkk.first ()

Output:

groupby () — very powerful feature with many variations. This makes the task of splitting a data frame according to some criteria really simple and efficient.

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically