Set value for particular cell in Pandas DataFrame using index

In this tutorial, we will learn how to set value for particular cell in Pandas DataFrame using index in Python? By Pranit Sharma Last updated : April 12, 2023

To set the value of a particular cell using index, use pandas.DataFrame.at[] property. The at[] property is used to find the position of a cell value. It takes two arguments; Index number and column name and it returns the respective cell value. This method can also be used to set the value of a particular cell.

Syntax

DataFrame.at['index','column_name']

Here, index refers to the number of rows which ranges from 0 to n-1.

Python code to set value for particular cell in Pandas DataFrame using index

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    "Name":['Hari','Mohan','Neeti','Shaily'],
    "Age":[25,36,26,21],
    "Gender":['Male','Male','Female','Female'],
    "Profession":['Doctor','Teacher','Singer','Student']
}

# Now, we will create DataFrame
df = pd.DataFrame(d)

# Printing the original DataFrame
print("Original DataFrame:\n")
print(df,"\n\n")

# Now, we will change the cell value
# In the name column, we will change the value 
# from Shaily to Astha
# For this we need to pass its row number i.e. 
# index and also the column name.
df.at[3,'Name'] = 'Astha'

# Now, Printing the modified DataFrame
print("Modified DataFrame:\n")
print(df)

Output

Original DataFrame:

     Name  Age  Gender Profession
0    Hari   25    Male     Doctor
1   Mohan   36    Male    Teacher
2   Neeti   26  Female     Singer
3  Shaily   21  Female    Student 


Modified DataFrame:

    Name  Age  Gender Profession
0   Hari   25    Male     Doctor
1  Mohan   36    Male    Teacher
2  Neeti   26  Female     Singer
3  Astha   21  Female    Student

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.