Sunday, September 22, 2024
Google search engine
HomeLanguagesHow to Set Cell Value in Pandas DataFrame?

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 module
import pandas as pd
 
# create a dataframe
# with 3 rows and 3  columns
data = pd.DataFrame({
    'name': ['sireesha', 'ravi', 'rohith', 'pinkey', 'gnanesh'],
    'subjects': ['java', 'php', 'html/css', 'python', 'R'],
    'marks': [98, 90, 78, 91, 87]
})
 
# set value at 6 th location for name column
data.at[5, 'name'] = 'sri devi'
 
# set value at 6 th location for subjects column
data.at[5, 'subjects'] = 'jsp'
 
 
# set value at 6 th location for marks column
data.at[5, 'marks'] = 100
 
# display
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




# create a dataframe
# with 3 rows and 3  columns
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'
   
# set value at 4 th location for subjects column
data.loc[4, 'subjects'] = 'react-js'
   
   
# set value at 4 th location for marks column
data.loc[4, 'marks'] = 80
 
# display
data


Output:

 

Method 3: Update the value for a particular cell in pandas using replace

Here, we are updating the “suraj” value to “Lazyroar” using Pandas replace.

Python3




# import pandas module
import pandas as pd
 
data.replace("suraj", "Lazyroar", inplace=True)
 
#display
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 module
import pandas as pd
 
data.iloc[[0,1,3],[0]] = 45
 
#display
display(data)


Output:

 

RELATED ARTICLES

Most Popular

Recent Comments