Pandas DataFrame iterrows() Method | Pandas Method
Last Updated :
02 Feb, 2024
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
df = pd.DataFrame([[ 2 , 2.5 , 100 , 4.5 , 8.8 , 95 ]], columns = [
'int' , 'float' , 'int' , 'float' , 'float' , 'int' ])
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
df = pd.DataFrame([[ 'Animal' , 'Baby' , 'Cat' , 'Dog' ,
'Elephant' , 'Frog' , 'Gragor' ]])
itr = next (df.iterrows())[ 1 ]
itr
|
Output :
Note: As iterrows returns a Series for each row, it does not preserve dtypes across the rows.
Share your thoughts in the comments
Please Login to comment...