python - 使用 df.replace() 将数字分配给 pandas 中的字符串
问题描述
我正在尝试将数字分配给数据框中的“性别”功能。我的代码如下:
df['Sex'] = df['Sex'].replace('male', 1, inplace = True)
df['Sex'] = df['Sex'].replace('female', 2, inplace = True)
但是,代码在数据框的“性别”特征中给出了“无”的结果。这段代码可能有什么问题?
解决方案
我认为您正在使用 pandas DataFramereplace
而不是需要 pandas .str.replace
。如果我没记错的话,这应该有效:
df['sex'] = df['sex'].str.replace('male',1)
df['sex'] = df['sex'].str.replace('female',2)
推荐阅读
- jquery - Reset modal input value when closed using jQuery and AJAX
- regex - 尝试使用 sublime 使用正则表达式在 tsv 文件中查找损坏的行。我有 310 列,但文件打破了 206 选项卡
- javascript - 如何获取多个附加文本框的值?
- python - Flask 是为 Python 2.7 而不是为 Python 3 安装的
- sql - 使用“LIKE”运算符的嵌套 MS Access SQL 查询
- vba - Excel (Office 365) 在执行 UDF 时自动重启
- node.js - mongodb中两个模式之间的关系使用猫鼬
- powershell - 如何防止在 Powershell foreach 中形成多个表?
- python - Pandas DataFrame 到多维 NumPy 数组
- math - 如何使用 adipart 获得标准偏差/标准误差 Beta 多样性?