Python 如何在列上循环.replace以将多个字符串更改为一个字符串?

Python 如何在列上循环.replace以将多个字符串更改为一个字符串?,python,loops,dataframe,replace,Python,Loops,Dataframe,Replace,我在数据框中有一列,我正在尝试将所有拼写错误/输入错误修复为正确的字符串,例如“femake”到“female”。有没有办法在一行代码中列出所有拼写错误,以便将它们全部更改为正确的变量。我有以下代码。如果循环可以工作,我将如何创建循环 mh2014['Gender'] = mh2014['Gender'].replace('f' and 'woman' and 'femail' and 'cis-female/femme' and 'female (cis)' and 'cis female'

我在数据框中有一列,我正在尝试将所有拼写错误/输入错误修复为正确的字符串,例如“femake”到“female”。有没有办法在一行代码中列出所有拼写错误,以便将它们全部更改为正确的变量。我有以下代码。如果循环可以工作,我将如何创建循环

mh2014['Gender'] = mh2014['Gender'].replace('f' and 'woman' and 'femail' and 'cis-female/femme' and 'female (cis)' and 'cis female' and 'femake', 'female')

您只需在要替换的字符串上循环:

misspellings = ['f', 'woman', 'femail', 'cis-female/femme', 'female (cis)', 'cis female', 'femake']
for s in misspellings:
    mh2014['Gender'] = mh2014['Gender'].replace(s, 'female')
而不是你认为的那样。从:

布尔运算符和or是所谓的短路运算符:它们的参数从左到右求值,结果确定后立即停止求值。例如,如果A和C为true,但B为false,则A和B和C不会计算表达式C。当用作常规值而不是布尔值时,短路运算符的返回值是最后计算的参数

例如:

>>> 'x' and 'y'  # 'x' is true so try next expression
'y'
>>> '' and 'y'  # '' is false so don't try next expression
''
>>> 'x' and ''  # Same as the first
''

假设这是您正在使用的Pandas数据帧,您只需将该列重新分配给列表理解,在列表理解中检查拼写错误:

misspellings = {'f', 'woman','femail','cis-female/femme','female (cis)','cis female','femake'}
mh2014['Gender'] = ["female" if entry in misspellings else entry for entry in mh2014['Gender']]
我们使用一个集合来加快拼写错误的查找,因为它有


如果您想添加更多的拼写错误,请修改拼写错误列表,如果列表对于硬代码来说很麻烦,可以从文件中加载该列表。

因为您在问题中使用了单词数据框,我希望它是熊猫

import pandas as pd
df = pd.read_excel('loation/to/myfile')
misspelled = set('f', 'woman', 'femail', 'cis-female/femme', 'female (cis)', 'cis female', 'femake')
df['Gender'] = df['Gender'].str.replace(misspelled, 'female')

这个问题让我有点困惑——你到底想循环什么,循环具体实现了什么?该列是否只包含拼写错误的单词,或者是您的问题的一部分,如何检测拼写错误?抱歉,我只是尝试将列出的某些字符串的每次出现都更改为“女性”,以努力清理数据。您是否有excel/csv文件,或者您只想替换示例中显示的数据?我认为OP不希望在待处理的字符串中实际包含“和”谢谢你的建议。我可能是在睡觉的时候使用和。纠正它