What is the DataFrame.__iter__() method of Pandas in Python?

Overview

In Python, the DataFrame.__iter__() method of Pandas is used to create an iterator instance that iterates through DataFrame or series info axis.

Syntax


DataFrame.__iter__()
Syntax

Parameters

This method does not take any argument value.

Return value

This method returns a Python iterator object.

Example

In the code below, we use this method to iterate through a Pandas DataFrame. We have a DataFrame that includes country names and yearly GDP values.

# Program
import pandas as pd
# initializing a nested list
data = [['China', 15, 2021], ['America', 21, 2021], ['Pakistan', 0.4, 2020]]
# Creating the DataFrame
df = pd.DataFrame(data, columns = ['Country', 'GDP', 'Year'])
# invoking __iter__()
for x in df.__iter__():
print(x)

Explanation

  • Line4: We create a nested list to create a DataFrame.
  • Line 6: We invoke pd.DataFrame() to create a DataFrame on the above created nested list and column names.
  • Line 8: We iterate through the DataFrame info axis.