How to Set Cell Value in Pandas DataFrame?
In this article, we will discuss how to set cell values in Pandas DataFrame in Python.
Method 1: Set value for a particular cell in pandas using dataframe.at
This method is used to set the value of an existing value or set a new record.
Python3
import pandas as pd
data = pd.DataFrame({
'name' : [ 'sireesha' , 'ravi' , 'rohith' , 'pinkey' , 'gnanesh' ],
'subjects' : [ 'java' , 'php' , 'html/css' , 'python' , 'R' ],
'marks' : [ 98 , 90 , 78 , 91 , 87 ]
})
data.at[ 5 , 'name' ] = 'sri devi'
data.at[ 5 , 'subjects' ] = 'jsp'
data.at[ 5 , 'marks' ] = 100
data
|
Output:
Method 2: Set value for a particular cell in pandas using loc() method
Here we are using the Pandas loc() method to set the column value based on row index and column name
Python3
data = pd.DataFrame({
'name' : [ 'sireesha' , 'ravi' , 'rohith' , 'pinkey' , 'gnanesh' ],
'subjects' : [ 'java' , 'php' , 'html/css' , 'python' , 'R' ],
'marks' : [ 98 , 90 , 78 , 91 , 87 ]
})
data.loc[ 4 , 'name' ] = 'siva nagulu'
data.loc[ 4 , 'subjects' ] = 'react-js'
data.loc[ 4 , 'marks' ] = 80
data
|
Output:
Method 3: Update the value for a particular cell in pandas using replace
Here, we are updating the “suraj” value to “geeks” using Pandas replace.
Python3
import pandas as pd
data.replace( "suraj" , "geeks" , inplace = True )
display(data)
|
Output:
Method 4: Update the value for a particular cell in pandas using iloc
Here, we are updating the value of multiple indexes of the 0th column to 45 using Python iloc.
Python3
import pandas as pd
data.iloc[[ 0 , 1 , 3 ],[ 0 ]] = 45
display(data)
|
Output:
Last Updated :
03 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...