How To Update Column Values In Python Pandas - Python Guides (2024)

In this Python tutorial, we will learn various methods for updating column values in Python pandas. We’ll use some built-in functions to understand different approaches to updating column values in Python Pandas.

As a Developer, while making the Python Project I got the requirement to update column values in Python Pandas.

Here we will see:

  • How to update column values in Python Pandas by using at()
  • How to update column values in Python Pandas by using replace()
  • How to update column values in Python Pandas by using iloc()
  • How to update column values in Python Pandas by using loc()
  • How to update the case of the column names in Python Pandas
  • How to update the column values in Python Pandas by using rename()
  • How to update Dataframe with different data lengths using update()
  • How to update Dataframe at a specific location using update()

Table of Contents

How to update column values in Python Pandas

In Python, there are primarily a few methods that are commonly used and important to understand when updating column values in Python Pandas.

How to update column values in Python Pandas by using at()

  • In this section, we will discuss how to update column values in Python Pandas by using replace().
  • First, we will create a dataframe using the pd.dataframe() function and data is stored in a data frame as rows and columns. As a result, it qualifies as a matrix and is helpful for data analysis.

Example:

import pandas as pdnew_val = {"Country_name": ['USA','Germany','Australia','China'],"Zip_Code": [1456,8723,9562,8652]}df = pd.DataFrame(new_val, index=[1,2,3,4])df

Here is the Screenshot of the following given code.

How To Update Column Values In Python Pandas - Python Guides (1)
  • Now after creating a dataframe, we will update the column value by using at() function
  • Based on the row index and column name, the at() method in pandas is used to extract a single value from a dataframe.
  • With the help of Python’s at() method, we can change a row’s value about a column one at a time.

Syntax:

Here is the Syntax of the dataframe.at()method in Python

Dataframe.at[rowIndex, columnLabel]

Note: This parameter takes two parameters row index and column label. If the arguments given as the row index and column labels are out of bounds or are missing from the dataframe, the key error is raised.

In this example, we have used the at() function with an index 4 of the data frame and column ‘Country_name’. Thus, the value of the column ‘Country_name’ at row index 4 gets modified.

Source Code:

df.at[4,'Country_name']='Albania'print(df)

Here is the implementation of the following given code.

How To Update Column Values In Python Pandas - Python Guides (2)

This is how we can update column values in the dataframe using at().

Read: Add row to Dataframe Python Pandas

How to update column values in Python Pandas by using replace()

  • Now let us understand how to update column values in Python Pandas using replace().
  • Any string within a data frame can have its value updated or changed using the replace() function in Python. The index and label values are not necessary to be given to it.
  • Column values can be changed using the DataFrame.replace() function (one value with another value on all columns). A new DataFrame is returned by this function, which accepts the parameters to replace, value, inplace, limit, regex, and method. When the inplace=True parameter is used, it replaces an existing DataFrame object and returns a result of None.

Syntax:

Here is the Syntax of the dataframe.replace() function in Python Pandas

DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
  • It consists of a few parameters
    • to_replace: Make a string, list, dictionary, regex, integer, float, or other data type, and specify the values to be replaced.
    • value: By default, it takes no value and specifies the value we want to be replaced.
    • inplace: whether to perform the operation in place. By default, it takes a false value.
    • limit: maximum gap to fill when moving forward or backward.
    • regex: if to replace and/or value should be treated as regex.
    • method: By default, it takes the ‘pad’ value and it is used for the replacement.

Example:

Let’s take an example and check how to update column values in Python Pandas using replace().

Source Code:

df.replace("Australia", "Argentina", inplace=True)print(df)

You can refer to the below Screenshot

How To Update Column Values In Python Pandas - Python Guides (3)

As you can see in the Screenshot we have discussed how to update column values in Python Pandas by using replace().

Read: Python Pandas Drop Rows Example

How to update column values in Python Pandas by using iloc()

  • In this section, we will discuss how to update column values in Python Pandas by using iloc().
  • By providing the index values of the corresponding row/column, one can update or change the value of the row/column using the Python iloc() method.

Example:

df.iloc[[1,3],[1]] = 100print(df)
  • In this instance, we have changed the value of rows 1, 3, and the first column, “Num,” to 100.
  • Using the iloc() function, we may even slice the rows provided to the function to modify the values of many rows at once.

Here is the Screenshot of the following given code.

How To Update Column Values In Python Pandas - Python Guides (4)

This is how to update column values in Python Pandas by using iloc().

Read: Pandas Delete Column

How to update column values in Python Pandas by using loc()

  • In this section, we will discuss how to update column values in Python Pandas by using loc().
  • Rows and columns of a pandas DataFrame are selected using loc. The simplicity of usage of DataFrame is one of its key benefits. When you use pandas, you can verify. DataFrame. To choose or filter DataFrame rows or columns, use the loc[] attribute.
  • By providing the labels of the columns and the index of the rows, the loc() method in Python can also be used to change the value of a row with respect to its columns.

Syntax:

Here is the Syntax of the loc() method in Python Pandas.

dataframe.loc[row index,['column-names']] = value

Example:

Let’s take an example and check how to update column values in Python Pandas by using loc().

Source Code:

df.loc[0:2,['index','Country_name']] = [100,'Angola']print(df)

Here is the implementation of the following given code.

How To Update Column Values In Python Pandas - Python Guides (5)

This is how to update the column values in Python Pandas by using loc().

Read: Python DataFrame to CSV

How to update the case of the column names in Python Pandas

  • Now let us understand how to update the case of the column names in Python Pandas.
  • All of the column names in our data have their initial letter capitalized, as you can see. Having a standard case for all of your column names is always preferred.

Example:

Let’s take an example and check how to update the case of the column names in Python Pandas.

Source Code:

df.columns.str.lower()print(df)

You can refer to the below Screenshot.

How To Update Column Values In Python Pandas - Python Guides (6)

In this example, we have understood how to update the case of the column names in Python Pandas.

Read: How to delete a column in pandas

How to update the column values in Python Pandas by using rename()

  • Now let us understand how to update the column values in Python Pandas by using rename().
  • Using the rename() function is one technique to rename the columns in a Pandas Dataframe. When we need to rename a few specific columns, this approach works well because we just need to supply information for the columns that need to be changed.

Syntax:

Let’s have a look at the Syntax and understand the working of the df.rename() function in Python.

DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=None, inplace=False, level=None, errors='ignore')

Example:

Here we will take an example and check how to update the column values in Python Pandas by using rename().

Source Code:

result=df.rename(columns={'Country_name': 'Country'})print(result)

Here is the execution of the following given code.

How To Update Column Values In Python Pandas - Python Guides (7)

This is how to update the column values in Python Pandas by using rename().

Read: How to Find Duplicates in Python DataFrame

How to update Dataframe with different data lengths using update()

  • In this section, we will discuss how to update Dataframe with different data lengths using update().
  • Let’s consider a situation where I need to update a dataframe with more records than the original dataframe. If I use the update() function, records will be updated up until the length matches the size of the initial dataframe.

Example:

Let’s take an example and check how to update Dataframe with different data lengths using update().

Source Code:

import pandas as pdnew_data = pd.DataFrame({'Cities_of_U.S.A': ['NewYork', 'California', 'Phenix City'],'new_val': [56,18,21]})print("Original Dataframe: ",new_data)result = pd.DataFrame({'new_val2':[4,5,6]})new_data.update(result)print("Changed Dataframe:",result)

Here is the implementation of the following given code.

How To Update Column Values In Python Pandas - Python Guides (8)

This is how to update Dataframe with different data lengths using an update().

Read: How to Convert Integers to Datetime in Pandas in Python

How to update Dataframe at a specific location using update()

  • In this section, we will discuss how to update Dataframe at a specific location using update().
  • I’ll change the values of a specified location in this example. Wemust first create a dataframe using the index argument, and then use the update method on it.

Example:

Let’s take an example and check how to update Dataframe at a specific location using update().

Source Code:

import pandas as pdnew_data = pd.DataFrame({'Cities_of_U.S.A': ['NewYork', 'California', 'Phenix City'],'new_val': [56,18,21]})print("Original Dataframe: ",new_data)new_result = pd.DataFrame({'new_val_2':[1,2]},index=[0,2])new_data.update(new_result)print("Modified Dataframe :",new_data)

Here is the execution of the following given code

How To Update Column Values In Python Pandas - Python Guides (9)

This is how to update Dataframe at a specific location using update().

You may also like to read the following Python Pandas tutorials.

  • Missing Data in Pandas in Python
  • Python Pandas DataFrame Iterrows
  • Crosstab in Python Pandas

In this article, we have discussed how to update column values in Python pandas. And also we have covered the following given topics.

  • How to update column values in Python Pandas by using at()
  • How to update column values in Python Pandas by using replace()
  • How to update column values in Python Pandas by using iloc()
  • How to update column values in Python Pandas by using loc()
  • How to update the case of the column names in Python Pandas
  • How to update the column values in Python Pandas by using rename()
  • How to update Dataframe with different data lengths using update()
  • How to update Dataframe at a specific location using update()

How To Update Column Values In Python Pandas - Python Guides (10)

Bijay Kumar

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

How To Update Column Values In Python Pandas - Python Guides (2024)
Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 6366

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.