In this post you will learn how to change the value of a cell in a dataframe in Pandas. I will show you two effective methods.
The dataframe in Pandas that the data scientist works with is usually a large table of data. Luckily, Pandas makes it easy to access every single cell. Pandas includes two functions that allow you to easily change the value of a single cell in a dataframe.
How to change the value of a cell using at method
The first function of the Pandas library that allows you to change the value of a single cell is the at method. It allows you to specify a row and a column as parameters to get the cell value.
import pandas as pd my_df = pd.DataFrame({'Column1': [2, 7, 6, 7], 'Column2': [2, 5, 8, 5], 'Column3': [4, 1, 9, 1]}) print(f'This is my dataframe: \n{my_df}') print(f'The value before the update: {my_df.at[0, "Column1"]}') my_df.at[0,'Column1'] = 792 print(f'The value after the update: {my_df.at[0, "Column1"]}')
As you can see in my example Python code we use the at method with which I got to the value of the cell. In the next step, I just assigned a different value and Pandas replaced it in the cell.
How to change the value of a cell using iat method
The second method of getting into a cell in Pandas is the iat method. The method works in a similar way to the at function. The only exception is that instead of the column name, it enters its index.
import pandas as pd my_df = pd.DataFrame({'Column1': [2, 7, 6, 7], 'Column2': [2, 5, 8, 5], 'Column3': [4, 1, 9, 1]}) print(f'This is my dataframe: \n{my_df}') print(f'The value before the update: {my_df.iat[1, 1]}') my_df.iat[1, 1] = 532 print(f'The value after the update: {my_df.iat[1, 1]}')
As you can see, thanks to the iat method, I got the value of the cell after entering the row and column indexes. In the next step, I assigned another value, which was replaced in the cell.
Thanks to my post, you already know how to get to a specific cell in your dataframe. You can also change the value of a single cell in Pandas.
See also:
Documentation of at and iat methods
How to rename columns
How to remove rows with certain values
1 thought on “How to change the value of a cell”