ADVERTISEMENT
ADVERTISEMENT

How to update a DataFrame in pandas while iterating row by row?

Learn how to update a DataFrame in pandas while iterating row by row?
Submitted by Pranit Sharma, on May 14, 2022

Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs.

In this article, we are going to learn how to update a DataFrame row while iterating? For this purpose, we are going to use pandas.DataFrame.iterrows() method.

pandas.DataFrame.iterrows() method

This special function allows us to iterate each row in the DataFrame.

Syntax:

DataFrame.iterrows()

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# Creating dictionary
d = {
    'Fruits':['Apple','Orange','Banana'],
    'Price':[50,40,30],
    'Vitamin':['C','D','B6']
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")


# Iterating rows and updating price 
# of each item by +10
for i,row in df.iterrows():
     price = 10
     if row['Price'] <=60:
          price += row['Price']
          df._set_value(i,'Price',price)

# Display modified DataFrame
print("Modified DataFrame\n",df)

Output:

Example: Update a DataFrame in pandas

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.