Pandas DataFrame.at
Pandas DataFrame.at
The DataFrame.at
property in pandas provides a fast and label-based way to access or modify a single value in a DataFrame. It is primarily used for accessing or setting scalar values in a DataFrame based on row and column labels.
Syntax
The syntax for accessing or modifying a value using DataFrame.at
is:
DataFrame.at[row_label, column_label]
Here, DataFrame
refers to the pandas DataFrame, and row_label
and column_label
are the labels for the row and column, respectively.
Parameters
row_label
: The label of the row to access or modify.column_label
: The label of the column to access or modify.
Returns
The value at the specified row and column in the DataFrame.
Examples
Accessing a Single Value
Use DataFrame.at
to access a specific value in a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# Access the age of Ram
print("Age of Ram:")
age_of_ram = df.at[1, 'Age']
print(age_of_ram)
Output
Age of Ram:
30
Modifying a Single Value
Use DataFrame.at
to modify a specific value in a DataFrame.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
# Update the salary of Priya
print("Updating Priya's Salary:")
df.at[2, 'Salary'] = 95000
print(df)
Output
Updating Priya's Salary:
Name Age Salary
0 Arjun 25 70000
1 Ram 30 80000
2 Priya 35 95000
Using DataFrame.at
with a Multi-Index
DataFrame.at
also supports MultiIndex DataFrames.
Python Program
import pandas as pd
# Create a MultiIndex DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Department': ['HR', 'Finance', 'IT'],
'Salary': [70000, 80000, 90000]
}
df = pd.DataFrame(data)
df.set_index(['Department', 'Name'], inplace=True)
# Access Priya's salary
print("Priya's Salary:")
salary_of_priya = df.at[('IT', 'Priya'), 'Salary']
print(salary_of_priya)
Output
Priya's Salary:
90000
Accessing a Value in a Non-Numeric Column
Use DataFrame.at
to access a non-numeric value, such as a string.
Python Program
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Arjun', 'Ram', 'Priya'],
'Age': [25, 30, 35],
'Department': ['HR', 'Finance', 'IT']
}
df = pd.DataFrame(data)
# Access the department of Arjun
print("Department of Arjun:")
department_of_arjun = df.at[0, 'Department']
print(department_of_arjun)
Output
Department of Arjun:
HR
Summary
In this tutorial, we explored the DataFrame.at
property in pandas. Key takeaways include:
- Using
DataFrame.at
for label-based access to scalar values. - Efficiently modifying specific values in a DataFrame.
- Supporting MultiIndex operations with
DataFrame.at
.
The DataFrame.at
property is an efficient and convenient way to access or update single values in a pandas DataFrame.