python - 如何根据不同熊猫列中的值替换字符串
问题描述
我正在清理数据集,如果 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
并返回该行。你可以使用df.apply
over 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
推荐阅读
- mysql - 从 Docker 容器运行 Spring Boot 应用程序时出错
- php - 从字符串的末尾开始,一旦到达字符组的第一次出现,如何停止捕获?
- azure - Azure 数据工厂与 App Insight
- python - 元素不可点击,因为另一个元素在 python 中隐藏了它
- debugging - 使用调试器从应用程序中删除函数调用
- python - python中如何弹出消息不干扰后续进程?
- database - 如果结果没有在客户端存根处解包,RPC 模型会发生什么?
- android - 在回收站视图中保留编辑文本
- c++ - VS2017:支持 WinXP 的增强二进制文件?
- windows-10 - 在 Windows Anaconda python 上安装 pytorch 时出现“找不到包错误”