在 Python pandas DataFrame 中交换值以清理数据的最佳方法是什么

What is the best way to swap values in Python pandas DataFrame to clean up the data

我有一个 DataFrame,其中 'Name' 列有一些错误。我创建了一个字典,其中键的拼写错误,值的拼写正确。用正确的拼写替换错误的拼写的最佳方法是什么?这就是我所做的。

for incorrect, correct in incorrect_to_correct.items():
    mask = s_df['Name'] == incorrect
    s_df.loc[mask, 'Name'] = correct

有更好的方法吗?有人告诉我,通常如果你在 pandas 中使用 for 循环,你应该重新考虑你在做什么?有没有更好的方法来清理数据?这个字典方法是"wrong"?我是 pandas 的新手,如有任何帮助,我们将不胜感激。谢谢!

我认为你可以通过 dict:

使用 replace
df.Name = df.Name.replace(incorrect_to_correct)

样本:

df = pd.DataFrame({'Name' : ["john","mary","jon", "mar"]})
print (df)
   Name
0  john
1  mary
2   jon
3   mar

incorrect_to_correct = {'jon':'john', 'mar':'mary'}

df.Name = df.Name.replace(incorrect_to_correct)
print (df)
   Name
0  john
1  mary
2  john
3  mary