You can use the following basic syntax to set the value for a specific cell in a pandas DataFrame:
#set value at row index 0 and column 'col_name' to be 99 df.at[0, 'col_name'] = 99
The following examples show how to use this syntax in practice with the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
Example 1: Set Value of One Cell in PandasÂ
The following code shows how to set the value in the 3rd index position of the ‘points’ column to 99:
#set value in 3rd index position and 'points' column to be 99 df.at[3, 'points'] = 99 #view updated DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 99 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
Notice that the value in the 3rd index position of the ‘points’ column was changed and all other values in the DataFrame remained the same.
Example 2: Set Value of Multiple Cells in Pandas
The following code shows how to set the value of multiple cells in a range simultaneously:
#set values in index positions 0 to 3 in 'points' column to be 99 df.at[0:3, 'points'] = 99 #view updated DataFrame df points assists rebounds 0 99 5 11 1 99 7 8 2 99 7 10 3 99 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
Example 3: Set Values Conditionally in Pandas
The following code shows how to set the values in the ‘rebounds’ column to be 99 only if the value in the points column is greater than 20:
#set values in 'rebounds' column to be 99 if value in points column is greater than 20
df.loc[df['points']>20, ['rebounds']] = 99
#view updated DataFrame
df
points assists rebounds
0 25 5 99
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 99
6 25 9 99
7 29 4 99
Notice that each value in the rebounds column was changed to 99 if the value in the points column was greater than 20.
All other values remained the same.
Additional Resources
The following tutorials explain how to perform other common functions in pandas:
How to Get Cell Value from Pandas DataFrame
How to Get First Row of Pandas DataFrame
How to Get First Column of Pandas DataFrame
How to Get Index of Rows Whose Column Matches Value in Pandas