Pandas iterrows update value in Python [4 Ways]

Do you want to use iterrows to update the dataframe? In this Pandas blog, I will explain how to use Pandas iterrows update value in Python using different examples.

To effectively update values in a DataFrame using Pandas in Python, iterrows() proves to be a versatile tool. Across four examples – a basic update, a row-wise operation, updating multiple values, and integration with other functions – it’s clear that iterrows() adapts well to different scenarios, demonstrating its practicality for both straightforward and complex data modifications.

Pandas iterrows update value in Python

The Pandas iterrows() is a generator that yields an index and row as a Series for each row in the DataFrame. It’s typically used for iterating over rows, but it can also be used to update values in Python.

To demonstrate how to update a value in a DataFrame using iterrows() in Python, let’s consider a basic example: Typically we combine it with at() or loc() function to update the DataFrame.

import pandas as pd

data = {
    'Store_ID': [1, 2, 3, 4, 5],
    'Products_Sold': [30, 45, 20, 35, 50]
}
df = pd.DataFrame(data)
print("Before Upadting:\n", df)

new_products_sold = 25
for index, row in df.iterrows():
    if row['Store_ID'] == 3:
        df.at[index, 'Products_Sold'] = new_products_sold
        # Update using 'loc'
        # df.loc[index, 'Products_Sold'] = new_products_sold
print("After Upadting:\n", df)

Output:

Before Upadting:
    Store_ID  Products_Sold
0         1             30
1         2             45
2         3             20
3         4             35
4         5             50
After Upadting:
    Store_ID  Products_Sold
0         1             30
1         2             45
2         3             25
3         4             35
4         5             50

The screenshot displayed below illustrates the output after the code has been processed in the Pycharm editor.

pandas iterrows change value in Python

There can be different ways to change value using Pandas iterrows:

1. iterrows change value in dataframe for row-wise operation

The Python iterrows() function in Pandas, iterates over DataFrame rows as index, row pairs. It’s useful for row-wise operations, but it’s slow for large datasets. Typically combined with at() or loc() to update the DataFrame.

Here is the full code for using Pandas iterrows update value in Python:

import pandas as pd

df = pd.DataFrame({
    'City': ['New York', 'Los Angeles', 'Chicago'],
    'Population': [8419000, 3971000, 2716000]
})
print("Before Updating:\n", df)
growth_rate = 1.02
for index, row in df.iterrows():
    df.at[index, 'Population'] = int(row['Population'] * growth_rate)
print("After Updating:\n", df)

Output:

Before Updating:
           City  Population
0     New York     8419000
1  Los Angeles     3971000
2      Chicago     2716000
After Updating:
           City  Population
0     New York     8587380
1  Los Angeles     4050420
2      Chicago     2770320

Upon the completion of code execution in Pycharm, the resulting output is depicted in the screenshot below.

Pandas iterrows update value in Python

2. iterrows update multiple values in DataFrame

Multiple value updates involve collecting changes first and then applying them all at once to the DataFrame in Python.

For instance:

import pandas as pd

df = pd.DataFrame({'State': ['California', 'Texas', 'New York'], 'Population': [0, 0, 0]})
print("Before Upadting:\n", df)

new_population_data = {'California': 39500000, 'Texas': 29000000, 'New York': 19500000}
updates = {index: new_population_data[row['State']] for index, row in df.iterrows()}
df['Population'].update(pd.Series(updates))
print("After Upadting:\n", df)

Output:

Before Upadting:
         State  Population
0  California           0
1       Texas           0
2    New York           0
After Upadting:
         State  Population
0  California    39500000
1       Texas    29000000
2    New York    19500000

Below is a screenshot taken following the implementation of the code in the Pycharm editor.

iterrows update value in Python

3. df iterrows change value with other function

Using Pandas iterrows update value in Python in combination with other methods can be helpful for specific, complex scenarios that require row-wise iteration along with group-wise or conditional operations.

For instance:

import pandas as pd

df = pd.DataFrame({'State': ['California', 'Texas'], 'GDP': [3000000, 1500000], 'Population': [39500000, 29000000], 'GDP per Capita': [0, 0]})
print("Before Upadting:\n", df)

for index, row in df.iterrows():
    df.loc[index, 'GDP per Capita'] = row['GDP'] / row['Population']
print("After Upadting:\n", df)

Output:

Before Upadting:
         State      GDP  Population  GDP per Capita
0  California  3000000    39500000               0
1       Texas  1500000    29000000               0
After Upadting:
         State      GDP  Population  GDP per Capita
0  California  3000000    39500000        0.075949
1       Texas  1500000    29000000        0.051724

Following the execution of the code in Pycharm, the resulting screenshot is displayed below.

dataframe iterrows change value in Python

Conclusion

Here, I have explained the versatility and utility of using iterrows() method for Pandas iterrows update value in Python. Through four distinct examples – a basic update, a row-wise operation, updating multiple values, and combining with other functions – we’ve seen how iterrows() function can be adapted to a variety of data manipulation tasks.

This demonstrates its flexibility in handling different types of data updates, whether they’re simple or involve more complex logic.

You may also like to read: