27. Accessing and Changing values of DataFrames
By Bernd Klein. Last modified: 26 Apr 2023.
We have seen in the previous chapters of our tutorial many ways to create Series and DataFrames. We also learned how to access and replace complete columns. This chapter of our Pandas and Python tutorial will show various ways to access and change selectively values in Pandas DataFrames and Series. We will show ways how to change single value or values matching strings or regular expressions.
For this purpose we will learn to know the methods loc, at and replace
We will work with the following DataFrame structure in our examples:
import pandas as pd
first = ('Mike', 'Dorothee', 'Tom', 'Bill', 'Pete', 'Kate')
last = ('Meyer', 'Maier', 'Meyer', 'Mayer', 'Meyr', 'Mair')
job = ('data analyst', 'programmer', 'computer scientist',
'data scientist', 'accountant', 'psychiatrist')
language = ('Python', 'Perl', 'Java', 'Java', 'Cobol', 'Brainfuck')
df = pd.DataFrame(list(zip(last, job, language)),
columns =['last', 'job', 'language'],
index=first)
df
| last | job | language | |
|---|---|---|---|
| Mike | Meyer | data analyst | Python |
| Dorothee | Maier | programmer | Perl |
| Tom | Meyer | computer scientist | Java |
| Bill | Mayer | data scientist | Java |
| Pete | Meyr | accountant | Cobol |
| Kate | Mair | psychiatrist | Brainfuck |
Changing one value in DataFrame
Pandas provides two ways, i.e. loc and at, to access or change a single value of a DataFrame. We will experiment with the height of Bill in the following Python code:
# accessing the job of Bill:
print(df.loc['Bill', 'job'])
# alternative way to access it with at:
print(df.at['Bill', 'job'])
# setting the job of Bill to 'data analyst' with 'loc'
df.loc['Bill', 'job'] = 'data analyst'
# let us check it:
print(df.loc['Bill', 'job'])
# setting the job of Bill to 'computer scientist' with 'at'
df.at['Pete', 'language'] = 'Python'
OUTPUT:
data scientist data scientist data analyst
The following image shows what we have done:

You will ask yourself now which one you should use? The help on the at method says the following: "Access a single value for a row/column label pair. Similar to loc, in that both provide label-based lookups. Use at if you only need to get or set a single value in a DataFrame or Series."
loc on the other hand can be used to access a single value but also to access a group of rows and columns by a label or labels.
Another intestering question is about the speed of both methods in comparison. We will measure the time behaviour in the following code examples: