Do you think IIT Guwahati certified course can help you in your career?
No
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.
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:
row_index: It provides the function with the index value of the row to be searched
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:
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
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
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
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
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
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
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.