The Wayback Machine - https://web.archive.org/web/20240718072846/https://www.geeksforgeeks.org/how-to-iterate-over-dataframe-groups-in-python-pandas/
Open In App

How to Iterate over Dataframe Groups in Python-Pandas?

Last Updated : 13 Sep, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In this article, we’ll see how we can iterate over the groups in which a data frame is divided. So, let’s see different ways to do this task.

First, Let’s create a data frame:

Python3




# import pandas library
import pandas as pd
 
# dictionary
dict = {'X': ['A', 'B', 'A', 'B'],
        'Y': [1, 4, 3, 2]}
 
# create a dataframe
df = pd.DataFrame(dict)
 
# show the dataframe
df


Output:

Iterate over Data frame Groups in Python-Pandas

Iterate over Data frame Groups in Python-Pandas

Using DataFrame.groupby()  to Iterate over Data frame Groups

DataFrame.groupby() function in Python is used to split the data into groups based on some criteria. 

Python3




# import pandas library
import pandas as pd
 
# dictionary
dict = {'X': ['A', 'B', 'A', 'B'],
        'Y': [1, 4, 3, 2]}
 
# create a dataframe
df = pd.DataFrame(dict)
 
# group by 'X' column
groups = df.groupby("X")
 
for name, group in groups:
    print(name)
    print(group)
    print("\n")


Output:

Iterate over Data frame Groups in Python-Pandas

In above example, we have grouped on the basis of column “X”. As there are two different values under column “X”, so our data frame will be divided into 2 groups. Then our for loop will run 2 times as the number groups are 2. “name” represents the group name and “group” represents the actual grouped data frame.

Using Dataframe.groupby() and Groupby_object.groups.keys() together

Groupby_object.groups.keys() method will return the keys of the groups.

Python3




# import pandas library
import pandas as pd
 
# dictionary
dict = {'X': ['A', 'B', 'A', 'B'],
        'Y': [1, 4, 3, 2]}
 
# create a dataframe
df = pd.DataFrame(dict)
 
# group by "X" column
groups = df.groupby('X')
 
# extract keys from groups
keys = groups.groups.keys()
 
for i in keys:
    print(groups.get_group(i))
    print('\n')


Output:

Iterate over Data frame Groups in Python-Pandas

In above example, we’ll use the function groups.get_group() to get all the groups. First we’ll get all the keys of the group and then iterate through that and then calling get_group() method for each key. get_group()  method will return group corresponding to the key.



Similar Reads

Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
How to iterate over rows in Pandas Dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Let’s see the how to iterate over rows in Pandas Dataframe using iterrows() and itertuples() :Method #1: Using the DataFrame.iterrows() m
2 min read
Different ways to iterate over rows in Pandas Dataframe
In this article, we will cover how to iterate over rows in a DataFrame in Pandas. Example # Defining a function to applydef print_row(row): print(f"Name: {row['Name']}, Age: {row['Age']}")# Iterating over rows using apply()df.apply(print_row, axis=1)[embed]https://www.youtube.com/watch?v=mT-2AxZLtvw&t=179s[/embed] Pandas Loop through RowsPandas
3 min read
How to Iterate over rows and columns in PySpark dataframe
In this article, we will discuss how to iterate rows and columns in PySpark dataframe. Create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf
6 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 min read
How to Iterate over months between two dates in Python?
In this article, we will discuss how to iterate over months between two dates using Python. We can iterate over months between two dates using timedelta and rrule methods. Method 1: Iteration using timedeltatimedelta() is used for calculating differences in dates and also can be used for date manipulations in Python Example: But using timedelta we
2 min read
three90RightbarBannerImg