Python Practice › Pandas Programs › Program 38
Change one value
Write a pandas program to change John’s age to 24.
Output
name age 0 Alex 30 1 John 24 2 Peter 29 3 Klaus 33
Approach
df.loc[condition, column] = value.
Solution
import pandas as pddf = pd.DataFrame({"name": ["Alex", "John", "Peter", "Klaus"], "age": [30, 27, 29, 33]})df.loc[df["name"] == "John", "age"] = 24print(df)Output
name age 0 Alex 30 1 John 24 2 Peter 29 3 Klaus 33
Line by line
Line 3
loc with a row condition and a column name changes the value in place.
Learn the concept
New to this topic? Read the lesson, then come back.