首页 > 解决方案 > 如何根据不同熊猫列中的值替换字符串

问题描述

我正在清理数据集,如果 B 列中的值与特定字符串匹配,我需要删除 A 列中的格式错误。

A       B
foo//,  cherry
bar//,  orange
bar//,  cherry
bar     apple

因此,在这种情况下,如果 B 列是“樱桃”,我想在 A 列中将“//”替换为“”。最终结果将如下所示。

A       B
foo,    cherry
bar//,  orange
bar,    cherry
bar     apple

非常感谢任何建议

标签: pythonpython-3.xpandasdata-cleaning

解决方案


您可以简单地编写一个函数,将一行作为series,检查cherry条件,修复字符串str.replace并返回该行。你可以使用df.applyover axis=1

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

推荐阅读