首页 > 解决方案 > 使用 df.replace() 将数字分配给 pandas 中的字符串

问题描述

我正在尝试将数字分配给数据框中的“性别”功能。我的代码如下:

df['Sex'] = df['Sex'].replace('male', 1, inplace = True)
df['Sex'] = df['Sex'].replace('female', 2, inplace = True)

但是,代码在数据框的“性别”特征中给出了“无”的结果。这段代码可能有什么问题?

标签: pythonpandas

解决方案


我认为您正在使用 pandas DataFramereplace而不是需要 pandas .str.replace。如果我没记错的话,这应该有效:

df['sex'] = df['sex'].str.replace('male',1)
df['sex'] = df['sex'].str.replace('female',2)

推荐阅读