Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Set Cell Value in Pandas DataFrame?

  • Last Updated : 28 Nov, 2021

In this article, we will discuss how to set cell values in Pandas DataFrame in Python.

Method 1: Using pandas.dataframe.at Method

This method is used to set the value for existing value or set a new record.

Syntax:

dataframe.at[index, 'column_name'] = value

where,

  • dataframe is the input dataframe
  • index is the position to insert
  • column_name is the column where value is inserted
  • value is the value to be inserted

Example:

Python3




# import pandas module
import pandas as pd
  
# create a dataframe
# with 3 rows amd 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
  
# set value at 4 th location for name column
data.at[4, 'name'] = 'siva nagulu'
  
# set value at 4 th location for subjects column
data.at[4, 'subjects'] = 'react-js'
  
  
# set value at 4 th location for marks column
data.at[4, 'marks'] = 80
  
# display
data

Output:

Method 2: Using loc() method

Here we are using loc() method to set the column value based on row index and column name

Syntax:

dataframe.loc[index, 'column_name'] = value

where,

  • dataframe is the input dataframe
  • index is the position to insert
  • column_name is the column where value is inserted
  • value is the value to be inserted

Example:

Python3




# import pandas module
import pandas as pd
  
# create a dataframe
# with 3 rows amd 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.loc[5, 'name'] = 'sri devi'
  
# set value at 6 th location for subjects column
data.loc[5, 'subjects'] = 'jsp'
  
  
# set value at 6 th location for marks column
data.loc[5, 'marks'] = 100
  
# set value at 4 th location for name column
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:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!