Pandas DataFrame iterrows() Method | Pandas Method
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:
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 :
Note: As iterrows returns a Series for each row, it does not preserve dtypes across the rows.