How can you replace the values in a specific column usi…
To replace the values in a column, you can use the pandas library to manipulate the data. Here is an example code using the pandas library:
import pandas as pd
# 创建一个示例数据框
data = {'Name': ['John', 'Mike', 'Sarah', 'Jessica'],
'Age': [28, 32, 25, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'San Francisco']}
df = pd.DataFrame(data)
# 使用.loc来替换某列的值
df.loc[df['Name'] == 'Mike', 'Age'] = 35
# 打印替换后的数据框
print(df)
The output result is:
Name Age City
0 John 28 New York
1 Mike 35 Los Angeles
2 Sarah 25 Chicago
3 Jessica 40 San Francisco
In this example, we used .loc to locate the rows that meet certain conditions and used the indexing operator ([]) to specify the columns to be replaced. Specifically, df.loc[df[‘Name’] == ‘Mike’, ‘Age’] signifies that for the rows where the Name column equals ‘Mike’, the value in the Age column is replaced with 35.