Python pandas – Update value of cell in DataFrame

In this post we will be creating a Python script that will update the value of a cell in a pandas DataFrame. To do this we will be using the ‘at()’ function typically used to get or set a single value within a DataFrame.

See the snippet of code below where we create a DataFrame consisting of three columns and rows.

import pandas as pd

df = pd.DataFrame(data={'A': [1, 2, 3, 4, 5 ],
                        'B': [73, 74, 75, 76, 77],
                        'C': [109, 110, 111, 112, 113]})

print(df)

The above would return the following as output.

   A   B    C
0  1  73  109
1  2  74  110
2  3  75  111
3  4  76  112
4  5  77  113
>>> 

Suppose we are wanting to update the value ‘1’ in column ‘A’ to ‘500’ instead, we would use the sample of code below using the ‘at()’ function.

df.at[0, 'A'] = '500'
print(df)

The ‘at()’ function will not create a new copy of our DataFrame, rather it updates the existing and so the above would return the following as output.

     A   B    C
0  500  73  109
1    2  74  110
2    3  75  111
3    4  76  112
4    5  77  113
>>> 

The code in this example could be changed to update the value of any one cell within a pandas DataFrame.

Take a look at some of our other content around the Python programming language here. Or check out our Pandas crash course by clicking here instead.

Leave a Reply