Pandas DataFrame 替换列中特定值:使用 replace() 方法
可以使用 replace() 方法来替换 DataFrame 中某列的特定值。以下是一个示例:
假设有一个 DataFrame df,其中有一列 'gender',其值为 'male' 和 'female',需要将 'male' 替换为 'M',将 'female' 替换为 'F'。
import pandas as pd
# 创建 DataFrame
data = {'name': ['Tom', 'Nick', 'John', 'Amy'],
'gender': ['male', 'female', 'male', 'female']}
df = pd.DataFrame(data)
# 使用replace()方法替换特定值
df['gender'] = df['gender'].replace({'male': 'M', 'female': 'F'})
print(df)
输出结果为:
name gender
0 Tom M
1 Nick F
2 John M
3 Amy F
在 replace() 方法中传递一个字典,字典的键是需要替换的值,字典的值是替换后的值。然后将替换后的列赋值给原始 DataFrame 中的对应列。
原文地址: http://www.cveoy.top/t/topic/qFMg 著作权归作者所有。请勿转载和采集!