我正在清理数据集,如果 B 列中的值与特定字符串匹配,我需要删除 A 列中的格式错误。
A B
foo//, cherry
bar//, orange
bar//, cherry
bar apple
因此,在这种情况下,如果 B 列是“樱桃”,我想将 A 列中的“//,”替换为“,”。最终结果如下所示。
A B
foo, cherry
bar//, orange
bar, cherry
bar apple
非常感谢任何建议
最佳答案
您可以简单地编写一个函数,将一行作为series
,检查cherry
条件,使用str.replace
修复字符串并返回该行。您可以在 axis=1
上使用 df.apply
。
def fix(s):
if s['B']=='cherry':
s['A']=s['A'].replace('//,',',')
return s
df.apply(fix, axis=1)
A B
0 foo, cherry
1 bar//, orange
2 bar, cherry
3 bar apple
关于python - 如何根据不同 pandas 列中的值替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65132356/