Table of contents
1.
Introduction
2.
What is pandas.at() Method?
2.1.
Pandas.at() method vs Pandas.loc() method
2.2.
Syntax
2.3.
Return Value of Pandas.at() method
2.4.
Time for an Example
2.5.
Python
3.
Errors of Pandas.at() method
3.1.
1. Out of Bounds Row Label
3.2.
Python
3.3.
2. Non-Existent Column Label
3.4.
Python
4.
Use Cases of Pandas.at Method
5.
Examples
5.1.
1. Updating a Single Value
5.2.
Python
5.3.
2. Conditional Value Update
5.4.
Python
5.5.
3. Data Validation
5.6.
Python
5.7.
Python
6.
Advantages of Pandas.at() Method
7.
Disadvantages of Pandas.at() Method
8.
Frequently Asked Questions
8.1.
Pandas.at() Method be used to modify an entire row or column?
8.2.
Is Pandas.at() Method create any new objects in memory?
8.3.
Pandas.at() Method can be used within conditional statements?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

pandas.at() Method

Author Dhruv Rawat
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In today's world, the manipulation of data is a fundamental aspect of data analysis and it plays an important role in extracting valuable insights from datasets. Pandas is a popular data manipulation library in Python which provides various methods for accessing, transforming, and modifying data. 

pandas.at() method


One such method is pandas.at(), which offers an easy and efficient way to access and modify specific elements in a DataFrame. 

In this article, we will be discussing the pandas.at() method with its syntax, errors and return value and discuss several working examples.

What is pandas.at() Method?

The pandas.at() method is used to access a single value from a DataFrame by specifying the row and column labels. It is similar to the loc() method, but it is more efficient for accessing a single value.

Pandas.at() method vs Pandas.loc() method

Let's see the key differences between the at and loc methods through a table:

Feature

at

loc

Efficiency

More efficient

Less efficient

Ease of use

Easier to use

More complex

Flexibility

Less flexible

More flexible

Use cases

Best for accessing a single value

Best for accessing multiple values or a slice of data

 

Syntax

Below is the syntax for using pandas.at() method:

DataFrame.at[row_index, column_label]


The pandas.at() method takes two parameters that are:

  1. row_index: It provides the function with the index value of the row to be searched
     
  2. column_label: It tells the function which column to look for the value in

Return Value of Pandas.at() method

The at() method in pandas returns the single element present at the specified row and column label position. The at() function will take the intersection value and then return the element.

Let us now discuss an example to see the working of the at() method. 

Time for an Example

Let us take a DataFrame representing a sales report:
 

  • Python

Python

import pandas as pd

data = {'Product': ['A', 'B', 'C', 'D'],
       'Sales': [1500, 2200, 1800, 1200]}

df = pd.DataFrame(data)
print("Original Sales Report:")
print(df)
You can also try this code with Online Python Compiler
Run Code

 

Output 

example of a data frame

In the above example, we start with a DataFrame, which has product names and their sales figures.

Let us now see the edge cases where at() method raises the exceptions.

Errors of Pandas.at() method

The at() method in pandas raises the KeyError exception if the provided row index is out of the bound. Similarly, if the provided column label does not exist or is out of bounds, it raises the KeyError exception.

Let us see some examples to understand the errors of pandas.at() method better:

1. Out of Bounds Row Label

In the below code, we attempt to access a value in the DataFrame using the at() method. 

However, since the DataFrame has only three rows with indices 0, 1, and 2, attempting to access the row with index 3 raises a KeyError. The code captures this exception and prints an error message indicating the specific KeyError that occurred.
 

  • Python

Python

# Import the pandas library as 'pd' for data manipulation and analysis

import pandas as pd

# Create a dictionary 'data' containing information about students, their courses, and scores

data = {'Student': ['Rahul', 'Sonia', 'Amit'],

       'Course': ['Computer Science', 'Mechanical', 'Electrical'],

       'Score': [85, 90, 78]}

# Create a DataFrame 'df' using the provided data dictionary

df = pd.DataFrame(data)

# Attempt to access a value in the DataFrame using 'at' method

try:

   # Try to access the value in the row with index 3 and column 'Score'

   df.at[3, 'Score']

except KeyError as e:

   # If the access raises a KeyError, print an error message with the specific KeyError

   print(f"KeyError: {e}")
You can also try this code with Online Python Compiler
Run Code

 

Output:

out of bounds row


The above code tries to access row index 3 and outputs a KeyError because the DataFrame only has indices 0, 1, and 2.

2. Non-Existent Column Label

In below code, we are trying to access a non-existing column 'GPA' using the at() method on the DataFrame. 

However, since the DataFrame only has columns 'Student', 'Course', and 'Score', attempting to access the column 'GPA' will raise a KeyError and prints an error message indicating the KeyError.
 

  • Python

Python

# Import the pandas library as 'pd' for data manipulation and analysis

import pandas as pd

# Create a dictionary 'data' containing information about students, their courses, and scores

data = {'Student': ['Rahul', 'Sonia', 'Amit'],

       'Course': ['Computer Science', 'Mechanical', 'Electrical'],

       'Score': [85, 90, 78]}

# Create a DataFrame 'df' using the provided data dictionary

df = pd.DataFrame(data)

# Attempt to access a non-existing column 'GPA' in the DataFrame using 'at' method

try:

   # Try to access the value in the row with index 0 and column 'GPA'

   df.at[0, 'GPA']

except KeyError as e:

   # If the access raises a KeyError, print an error message with the specific KeyError

   print(f"KeyError: {e}")
You can also try this code with Online Python Compiler
Run Code


Output:

non-existent column label


The above code outputs a KeyError because we are trying to access the column 'GPA' that doesn't exist in the DataFrame.

Use Cases of Pandas.at Method

The pandas.at() method has various use cases, such as:

  • Data Correction: pandas.at() is used to correct a single value in a DataFrame. For example, if we accidentally type the wrong number in a cell, pandas.at() can fix it
     
  • Conditional Updates: pandas.at() is used to update values in a DataFrame based on some specific conditions. For example, we can use pandas.at() to increase the price of all products in a DataFrame that crossed its expiry date
     
  • Data Validation: pandas.at() is used to put constraints on individual cell values in a DataFrame. For example, we can use pandas.at() to check if the value in a cell is within a certain range or not

Examples

Let us see some examples to understand the pandas.at() method better:

1. Updating a Single Value

In the below code, first, we create a DataFrame called 'df' using the provided data dictionary. Then, use the at() method to modify the value in the row with index one and column 'Score' to 95.

After that, we print the updated DataFrame to see the changes. 

  • Python

Python

# Import the pandas library as 'pd' for data manipulation and analysis

import pandas as pd

# Create a dictionary 'data' containing information about students, their courses, and scores

data = {'Student': ['Rahul', 'Sonia', 'Amit'],

       'Course': ['Computer Science', 'Mechanical', 'Electrical'],

       'Score': [85, 90, 78]}

# Create a DataFrame 'df' using the provided data dictionary

df = pd.DataFrame(data)

# Modify the value in the row with index 1 and column 'Score' to 95

df.at[1, 'Score'] = 95

# Print the updated DataFrame

print(df)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Before updating a single value:

before updating single value

After updating a single value:

after updating a single value


In the above code, we update Sonia's engineering score to 95 using pandas.at(). The DataFrame shows the modified scores.

2. Conditional Value Update

In the below code, we iterate through each row of the DataFrame and check if the 'Score' value is less than 80. If this condition is met, the score is increased by 5 using the at() method. 

  • Python

Python

for index, row in df.iterrows():

   if row['Score'] < 80:

       df.at[index, 'Score'] += 5

print(df)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Before conditional value update:

before conditional value update


After conditional value update:

after conditional value update


The above code increases the scores which are below 80 by using pandas.at() by five. The output shows the increased scores for students.

3. Data Validation

The below code creates a DataFrame 'df' using the provided student data, including their names, courses, and scores. It then iterates through the DataFrame and uses the at() method to ensure that all scores are within the valid range of 0 to 100. If not, then update them accordingly. 

  • Python

Python

# Import the pandas library as 'pd' for data manipulation and analysis
import pandas as pd

# Create a dictionary 'data' containing information about students, their courses, and scores
data = {
'Student': ['Rahul', 'Sonia', 'Amit', 'laxman', 'Raj'],
'Course': ['Computer Science', 'Mechanical', 'Electrical', 'Chemicals', 'Production'],
'Score': [-5, 120, 78, 139, -20] # Intentionally include values outside the range
}

# Create a DataFrame 'df' using the provided data dictionary
df = pd.DataFrame(data)

# Print the original DataFrame
print(df)
You can also try this code with Online Python Compiler
Run Code

Output:

original data frame without data validation


Now let us apply the validation check on the above data frame using the following code :

  • Python

Python

# Validate and correct scores that are out of bounds
for index, row in df.iterrows():
if row['Score'] < 0:
df.at[index, 'Score'] = 0
elif row['Score'] > 100:
df.at[index, 'Score'] = 100

# Print the updated DataFrame
print(df)
You can also try this code with Online Python Compiler
Run Code

Output:

after data validation output


In the above code pandas.at() is used to validate the scores in the range of 0-100. The Output shows the updated DataFrame, which has accurate scores while respecting valid limits like if the score <0, then it is updated to 0, and the score>100 is updated to 100.

Advantages of Pandas.at() Method

Let us discuss some of the advantages of using pandas.at() method:

  • It is very easy to use as we need to pass the row index and column label in order to access the particular value and update it
     
  • The pandas.at() method only access the value which we pass, which makes it fast and effective when working with large datasets
     
  • The pandas.at() method can be used to assign any data to a cell, whether it is a string, number, list etc. This features makes it flexible

Disadvantages of Pandas.at() Method

Let us discuss some of the Disadvantages of using pandas.at() method:

  • When working with large datasets, the pandas.at() method could be slow and less efficient than other methods to access the data
     
  • Not so flexible when compared to other methods for accessing data in a DataFrame, such as the loc method
     
  • It can be difficult at times during complex calculations like when calculating the sum or differences pandas.at() method is not successful

Frequently Asked Questions

Pandas.at() Method be used to modify an entire row or column?

No, we cannot modify entire rows or columns using the pandas.at() because it is made to access only single-cell values. In order to do so, we can make use of other methods like loc[] or iloc[] .

Is Pandas.at() Method create any new objects in memory?

No, pandas.at() does not create a new object in memory because it directly accesses and modifies the cell value, contributing to its memory efficiency and better performance.

Pandas.at() Method can be used within conditional statements?

Yes, pandas.at() can be used within conditional statements in order to update specific values based on conditions, allowing data-driven transformations.

Conclusion

Congratulations, you did a fantastic job!!. This article has reviewed a comprehensive guide to Pandas at() and its syntax, errors and return value and discussed several working examples. At last, some frequently asked questions are discussed.

Here are some more related articles:
 

Check out The Interview Guide for Product Based Companies and some famous Interview Problems from Top Companies, like AmazonAdobeGoogle, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

We hope you liked this article.


"Have fun coding!”

Live masterclass