How to Update Values in a Pandas DataFrame in Python

There are several ways to update values in a Pandas DataFrame in Python. In this article, I’ll show you various approaches to values of a Pandas DataFrame in Python. I have an another article How to Create a Pandas DataFrame in Python, where you will learn how to create a DataFrame. For this tutorial, I’ll use the below DataFrame:

       id      name  math_score
0  202301    Minhaj          92
1  202302   Ridhwan          86
2  202303   Tanveer          76
3  202304  Sharodia          89
4  202305      Alve          99
5  202306   Intisar          99

One way is to use the at property to update the value of a specific cell, using the row label and column label. Here’s an example:

df.at[row_label, column_label] = new_value

Another way is to use the iat property to update the value of a specific cell, using the row position and column position. Here’s an example:

df.iat[row_index, column_index] = new_value

You can also use the loc property to select a specific subset of rows and columns, and then update the values in that subset directly. Here’s an example:

df.loc[row_label, column_label] = new_value

You could also use the iloc property to select a specific subset of rows and columns, and then update the values in that subset directly. Here’s an example:

df.iloc[row_index, column_index] = new_value

You can also update the value of DataFrame using where() method to update only the selected rows.

df.where(condition, new_value, inplace=True)

If you want to update multiple columns or rows at once, you can use the update() method, which takes a DataFrame or a series with the new values and aligns it with the original DataFrame by index and column labels. Here’s an example:

df.update(new_df)

In this tutorial, I tried to brief how to count the number of rows and columns of a Pandas DataFrame in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.

Add a Comment