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.

- 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.

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

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.

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.

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.

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.

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.

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

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()
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.
FAQs
How do I update a column in a csv file in Python? ›
- Import module.
- Open CSV file and read its data.
- Find column to be updated.
- Update value in the CSV file using to_csv() function.
You can use df. replace({"Courses": dict}) to remap/replace values in pandas DataFrame with Dictionary values. It allows you the flexibility to replace the column values with regular expressions for regex substitutions.
How do I edit a column in a DataFrame in Python? ›- Rename columns. Use rename() method of the DataFrame to change the name of a column. See rename() documentation here. ...
- Add columns. You can add a column to DataFrame object by assigning an array-like object (list, ndarray, Series) to a new column using the [ ] operator. ...
- Delete columns. In [7]: ...
- Insert/Rearrange columns.
To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.
How do you update DataFrame values? ›- Set cell values in the entire DF using replace() ...
- Change value of cell content by index. ...
- Modify multiple cells in a DataFrame row. ...
- Update cells based on conditions. ...
- Set and Replace values for an entire Pandas column / Series. ...
- Replace string in Pandas DataFrame column.
pandas. DataFrame. replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame.
How do I change the value of a column in a CSV file? ›- Step 1: Import the module. To import. ...
- Step 2 : Read the csv file. ...
- Step 3 : Change the date format. ...
- Step 4 : Convert column names to lowercase. ...
- Step 5 : Replacing Empty spaces with underscore. ...
- Step 6 : Rename the column names. ...
- Step 7 : Check for Missing Values. ...
- Step 8 : Filling Missing Data.
The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...
Can you modify the value in a dictionary? ›Modifying values in a dictionary
Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value. dictionary: A collection of key-value pairs.
Values of a Python Dictionary can be updated using the following two ways i.e. using the update() method and also, using square brackets. Dictionary represents the key-value pair in Python, enclosed in curly braces. The keys are unique and a colon separates it from value, whereas comma separates the items.
How do you replace values in a column based on condition in PySpark? ›
You can replace column values of PySpark DataFrame by using SQL string functions regexp_replace(), translate(), and overlay() with Python examples.
How do I rewrite a column in pandas? ›In order to replace a value in Pandas DataFrame, use the replace() method with the column the from and to values. Below example replace Spark with PySpark value on the Course column. Notice that all the Spark values are replaced with the Pyspark values under the first column.
How do you manipulate data in a column in a DataFrame? ›If you want to modify a single column in a dataframe, use map() If you want to modify several columns in a dataframe at once, use apply() If you want to perform aggregate functions on columns or rows in a dataframe, use apply()
What commands changes the value in a column? ›Altering (Changing) a Column's Default Value
You can change a default value for any column by using the ALTER command.
The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You should also use the ALTER TABLE command to add and drop various constraints on an existing table.
How do you update multiple column values? ›We can update multiple columns in SQL using the UPDATE command. The UPDATE statement is followed by a SET statement, which specifies the column(s) where the update is required. Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...
How do you update a variable value in Python? ›In Python += is used for incrementing, and -= for decrementing. In some other languages, there is even a special syntax ++ and -- for incrementing or decrementing by 1. Python does not have such a special syntax. To increment x by 1 you have to write x += 1 or x = x + 1 .
How do you update a value in a table in Python? ›- import mysql. connector package.
- Create a connection object using the mysql. connector. ...
- Create a cursor object by invoking the cursor() method on the connection object created above.
- Then, execute the UPDATE statement by passing it as a parameter to the execute() method.
An SQL UPDATE statement changes the data of one or more records in a table. Either all the rows can be updated, or a subset may be chosen using a condition. The UPDATE statement has the following form: UPDATE table_name SET column_name = value [, column_name = value ...]
How do you replace all values in a column in a data frame? ›Suppose that you want to replace multiple values with multiple new values for an individual DataFrame column. In that case, you may use this template: df['column name'] = df['column name']. replace(['1st old value', '2nd old value', ...], ['1st new value', '2nd new value', ...])
How do you apply a function to all values of a column in pandas? ›
- Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
- Print input DataFrame, df.
- Override column x with lambda x: x*2 expression using apply() method.
- Print the modified DataFrame.
...
Stepwise Implementation
- Step 1: View Existing CSV File. ...
- Step 2: Create New DataFrame to Append. ...
- Step 3: Append DataFrame to Existing CSV File.
If you input a new formula that is different from existing formulas in a calculated column, the column will automatically update with the new formula.
How do you UPDATE data in a database using Python? ›- Step 1: Create a Database and Table. If you haven't already done so, create a database and table in SQL Server. ...
- Step 2: Connect Python to SQL Server. ...
- Step 3: Update the Records in SQL Server using Python. ...
- Step 4: Check that the record was updated.
- Enable-Migrations -ContextTypeName CodeFirstExistingDB.StoreContext.
- Add-Migration InitialCreate -IgnoreChanges.
- namespace CodeFirstExistingDB. { ...
- Add-Migration add_product_description.
- namespace CodeFirstExistingDB.Migrations. {
DataFrame - assign() function
The assign() function is used to assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. The column names are keywords.
- Step 1: Create a Database. ...
- Step 2: Create a Table and Insert the data. ...
- Step 3: View the Table before updating the values. ...
- Step 4: Change the value of a particular column in the table. ...
- Step 5: View the Table after updating the values.
You cannot update the value of the identity column in SQL Server using UPDATE statement. You can delete the existing column and re-insert it with a new identity value. The only way to remove the identity property for the column is by removing the identity column itself.
How do you update a column in an existing table? ›The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
How do you assign a value to a new column in Python? ›You can use the assign() function to add a new column to the end of a pandas DataFrame: df = df. assign(col_name=[value1, value2, value3, ...])