我在数据框中有一个列,我正在尝试将所有拼写错误/输入错误修复为正确的字符串(例如,“ 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')
假设这是您使用的Pandas DataFrame,您可以简单地将列重新分配给列表推导,在其中您可以检查拼写错误,例如:
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']]
我们使用一个集合来加快对拼写错误的查找,因为它具有O(1) average search time。
如果要添加更多拼写错误以进行捕获,请修改拼写错误列表,如果列表变得繁琐而难以硬编码,则可以从文件中加载它。
您只需要遍历要替换的字符串:
misspellings = ['f', 'woman', 'femail', 'cis-female/femme', 'female (cis)', 'cis female', 'femake']
for s in misspellings:
mh2014['Gender'] = mh2014['Gender'].replace(s, 'female')
and
不执行您认为的操作。从Python Tutorial:
布尔运算符
and
和or
是所谓的short-circuit运算符:它们的自变量从左到右进行求值,并且一旦确定结果就停止求值。例如,如果A
和C
为true,但B
为false,则A and B and 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
''
由于您在问题中使用了单词数据框,所以我希望它以熊猫为准。
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')