To set a value in a pandas DataFrame, the easiest way is to use the pandas at() function.
df.at[row,column] = value
The pandas set_value() method was deprecated in version 0.21.
When working with data, the ability to update fields on the fly can be very useful. We can use the pandas at() function to set values in a DataFrame or a Series.
Let’s say we have the following DataFrame.
df = pd.DataFrame({'Age': [43,23,71,49,52,37],
'Test_Score':[90,87,92,96,84,79]})
print(df)
# Output:
Age Test_Score
0 43 90
1 23 87
2 71 92
3 49 96
4 52 84
5 37 79
To set a value in this DataFrame, we can use the pandas at() function. Let’s say we want to update the 4th row’s Age from 49 to 51. We can do this easily in the following Python code.
df.at[3,"Age"] = 51
print(df)
# Output:
Age Test_Score
0 43 90
1 23 87
2 71 92
3 51 96
4 52 84
5 37 79
If you want to set a value based on integer positions of the columns, you can use the pandas iat() function.
df.iat[3,0] = 51
print(df)
# Output:
Age Test_Score
0 43 90
1 23 87
2 71 92
3 51 96
4 52 84
5 37 79
Setting a New Value in a Series in pandas
We can also set values in Series using the pandas at() function.
Let’s say we have the following Series.
ser = pd.Series(df["Age"])
print(ser)
0 43
1 23
2 71
3 51
4 52
5 37
Name: Age, dtype: int64
To set a value in a Series, pass the index you want to change to at() and then set it to the value you want.
ser.at[1] = 25
print(ser)
0 43
1 25
2 71
3 51
4 52
5 37
Name: Age, dtype: int64
Hopefully this article has helped you understand how to set values in pandas DataFrames and Series.