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

Pandas DataFrame iterrows() Method

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

iterrows() method in Pandas is a simple way to iterate over rows of a DataFrame. It returns an iterator that yields each row as a tuple containing the index and the row data (as a Pandas Series). This method is often used in scenarios where row-wise operations or transformations are required.

Example:

Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 32]})
# Iterating through the DataFrame
for index, row in df.iterrows():
    print(f"Index: {index}, Name: {row['Name']}, Age: {row['Age']}")

Output
Index: 0, Name: Alice, Age: 25
Index: 1, Name: Bob, Age: 32

This example demonstrates how iterrows() allows you to access each row’s data conveniently.

How does iterrows() Method Work?

In simple terms, iterrows() is a generator function. It generates a sequence of (index, row) pairs as you loop through your DataFrame. The index is the row label (or the row number if no custom index is set), and row is a Series object where each value corresponds to a column in that row.

Behind the scenes, iterrows() works by iterating over the DataFrame one row at a time:

  1. Row-by-Row Iteration: It loops over each row in the DataFrame, starting from the first row to the last.
  2. Index and Row: During each iteration, it returns the index (row label) and the row data as a Series.
  3. Efficient for Small Datasets: This method is effective when you need to process rows individually, but it’s not the fastest for large datasets.

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. Typically used in a for loop to process each row individually.

Iterating Over the DataFrame: Examples

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

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

Python
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 rows involving multiple columns using Pandas DataFrame.iterrows() function.

Python
import pandas as pd

df = pd.DataFrame({'Product': ['A', 'B', 'C'],'Price': [10, 20, 15],'Quantity': [100, 50, 200]
})
# Calculate total sales for each product
for index, row in df.iterrows():
    total_sales = row['Price'] * row['Quantity']
    print(f"Product {row['Product']} generated ${total_sales} in sales.")

Output
Product A generated $1000 in sales.
Product B generated $1000 in sales.
Product C generated $3000 in sales.

Example 3: Adding New Columns Using Iteration

We can also, add the new column in this case we’ll add 'Category' column using df.at[index, 'Category'] to assign a value for each row based on a condition.

Python
import pandas as pd

df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'],'Age': [25, 32, 37]})

# Adding a new column based on conditions
for index, row in df.iterrows():
    if row['Age'] > 30:
        df.at[index, 'Category'] = 'Senior'
    else:
        df.at[index, 'Category'] = 'Junior'
print(df)

Output
      Name  Age Category
0    Alice   25   Junior
1      Bob   32   Senior
2  Charlie   37   Senior

The code demonstrates how to use the iterrows() method in pandas to iterate over each row of a DataFrame, and based on a condition, add a new column called 'Category' to classify individuals as either “Senior” or “Junior”.

Conclusion : Key Takeways

  • Data Type Preservation: The row data returned by iterrows() is a Series. This means that the original data types of columns may not always be preserved.
  • Performance:
    • While iterrows() is straightforward, it can be slow for large DataFrames because it processes one row at a time and creates copies of each row.
    • For better performance, consider alternatives like itertuples() or vectorized operations.
  • For larger datasets or performance-critical tasks, consider alternatives like:
    • itertuples(): Faster and more memory-efficient.
    • Vectorized operations: Ideal for bulk computations without explicit loops.

Pandas DataFrame iterrows() Method | Pandas Method – FAQs

What is the basic difference between iterrows () and iteritems ()?

iterrows() iterates over rows (returns index and row data), while iteritems() iterates over columns (returns column names and values). iterrows() is used for row-wise operations, iteritems() for column-wise.

What is iteration in Pandas?

Iteration in pandas refers to looping through DataFrame rows or columns to perform operations or extract information. It allows for row-wise or column-wise processing of the data.

What is the function of Iter_rows?

iterrows() allows iteration over DataFrame rows, returning the index and the row data as a Series. It’s useful for applying operations to individual rows in a loop.

What are 3 types of iteration?

The three common types of iteration in pandas are:

  • Row iteration (using iterrows())
  • Column iteration (using iteritems())
  • Iteration over index (using itertuples() or df.index)


Next Article

Similar Reads

three90RightbarBannerImg