close
The Wayback Machine - https://web.archive.org/web/20241002131545/https://www.geeksforgeeks.org/pandas-dataframe-iterrows/
Open In App

Pandas DataFrame iterrows() Method | Pandas Method

Last Updated : 02 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series.

Example:

Python




import pandas as pd
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 32, 37]
})
for index, row in df.iterrows():
    print(f"Row {index} data:")
    print(f"Name: {row['Name']}, Age: {row['Age']}")


Output:

Row 0 data:
Name: Alice, Age: 25
Row 1 data:
Name: Bob, Age: 32
Row 2 data:
Name: Charlie, Age: 37

Syntax

Syntax: DataFrame.iterrows()

Yields: 

  • index- The index of the row. A tuple for a MultiIndex 
  • data- The data of the row as a Series 

Returns: it: A generator that iterates over the rows of the frame

Examples

Let’s understand how to iterate over the rows of DataFrame using iterrows method of Pandas library:

Example 1: 

In the below example, we use Pandas DataFrame.iterrows() to iter over numeric DataFrame rows.

Python3




import pandas as pd
  
# Creating a data frame along with column name
df = pd.DataFrame([[2, 2.5, 100, 4.5, 8.8, 95]], columns=[
                  'int', 'float', 'int', 'float', 'float', 'int'])
  
# Iter over the data frame rows
# # using df.iterrows()
itr = next(df.iterrows())[1]
itr


Output:

Pandas DataFrame iterrows example output

Example 2:

In the example, we iterate over the DataFrame having no column names using Pandas DataFrame.iterrows() function

Python3




import pandas as pd
  
# Creating a data frame
df = pd.DataFrame([['Animal', 'Baby', 'Cat', 'Dog',
                    'Elephant', 'Frog', 'Gragor']])
  
# Iterating over the data frame rows
# using df.iterrows()
itr = next(df.iterrows())[1]
itr


Output :

Pandas DataFrame iterrows example output

Note: As iterrows returns a Series for each row, it does not preserve dtypes across the rows.



Previous Article
Next Article

Similar Reads

Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for 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.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Python | Pandas DataFrame.fillna() to replace Null values in 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. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for 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.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
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. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
How to select the rows of a dataframe using the indices of another dataframe?
Prerequisites: PandasRandom Using Pandas module it is possible to select rows from a data frame using indices from another data frame. This article discusses that in detail. It is advised to implement all the codes in jupyter notebook for easy implementation. Approach:Import moduleCreate first data frame. In the example given below choice(), randin
2 min read
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
How to Transform Spark DataFrame to Polars DataFrame?
Apache Spark and Polars are powerful data processing libraries that cater to different needs. Spark excels in distributed computing and is widely used for big data processing, while Polars, a newer library, is designed for fast, single-machine data processing, leveraging Rust for performance. Sometimes, you might want to transform a Spark DataFrame
3 min read
Pandas DataFrame.dropna() Method
Pandas is one of the packages that makes importing and analyzing data much easier. Sometimes CSV file has null values, which are later displayed as NaN in Pandas DataFrame. Pandas dropna() method allows the user to analyze and drop Rows/Columns with Null values in different ways. Pandas DataFrame.dropna() Syntax Syntax: DataFrameName.dropna(axis=0,
3 min read
Python | Pandas Dataframe/Series.head() method
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. Pandas head() method is used to return top n (5 by default) rows of a data frame or series. Syntax: Dataframe.head(n=5) Parameters: n: i
2 min read
Python | Pandas Dataframe/Series.tail() method
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. Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series. Syntax: Dataframe.tail(n=5) Parameters: n
2 min read
Pandas dataframe.nunique() Method
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. Pandas DataFrame.nunique Syntax Pandas dataframe.nunique() function returns a Series with a number of distinct observations over the req
2 min read
Pandas DataFrame.to_sparse() Method
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.to_sparse Pandas Da
2 min read
Python | Pandas DataFrame.to_html() method
With help of DataFrame.to_html() method, we can get the html format of a dataframe by using DataFrame.to_html() method. Syntax : DataFrame.to_html() Return : Return the html format of a dataframe. Example #1 : In this example we can say that by using DataFrame.to_html() method, we are able to get the html format of a dataframe. # import DataFrame i
1 min read
Python | Pandas DataFrame.to_latex() method
With the help of DataFrame.to_latex() method, We can get the dataframe in the form of latex document which we can open as a separate file by using DataFrame.to_latex() method. Syntax : DataFrame.to_latex() Return : Return the dataframe as a latex document. Example #1 : In this example we can say that by using DataFrame.to_latex() method, we are abl
1 min read
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value,
2 min read
DataFrame.to_excel() method in Pandas
The to_excel() method is used to export the DataFrame to the excel file. To write a single object to the excel file, we have to specify the target file name. If we want to write to multiple sheets, we need to create an ExcelWriter object with target filename and also need to specify the sheet in the file in which we have to write. The multiple shee
2 min read
DataFrame.read_pickle() method in Pandas
Prerequisite : pd.to_pickle method() The read_pickle() method is used to pickle (serialize) the given object into the file. This method uses the syntax as given below : Syntax: pd.read_pickle(path, compression='infer') Parameters: Arguments Type DescriptionpathstrFile path where the pickled object will be loaded.compression{'infer', 'gzip', 'bz2',
2 min read
Pandas DataFrame describe() Method
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. Pandas DataFrame describe()Pandas describe() is used to view some basic statistical details like percentile, mean, std, etc. of a data f
4 min read
Pandas DataFrame.loc[] Method
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame loc[] SyntaxPandas
6 min read
Pandas DataFrame quantile() Method | Find Quantile Values
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier.  Pandas quantile() function returns values at the given quantile over the requested axis.  Note: In each of any set of values of a variate which
2 min read
Pandas DataFrame round() Method | Round Values to Decimal
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier.  Pandas round() function rounds a DataFrame value to a number with given decimal places. This function provides the flexibility to round differe
2 min read