pandas 串替换管子字符不起作用吗? [英] Pandas str.replace of pipe character not working?

查看:25
本文介绍了 pandas 串替换管子字符不起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 pandas str.Replace on Series时遇到了一个问题。我在Jupyter笔记本中使用了 pandas (尽管结果与普通的Python脚本相同)。

import pandas as pd
s = ["abc | def"]
df = pd.DataFrame(data=s)

print(s[0].replace(" | ", "@"))
print(df[0].str.replace("| ", "@"))
print(df[0].map(lambda v: v.replace("| ", "@")))

以下是结果

ipython Untitled1.py 

abc@def
0    @a@b@c@ @|@ @d@e@f@
Name: 0, dtype: object
0    abc @def
Name: 0, dtype: object

推荐答案

如果您退出管道,它将起作用。

>>> df[0].str.replace(" | ", "@")
0    abc@def
Name: 0, dtype: object

str.replace函数等价于re.sub

import re

>>> re.sub(' | ', '@', "abc | def")
'abc@|@def'

>>> "abc | def".replace(' | ', '@')
'abc@def'

Series.str.replace(pat, repl, n=-1, case=True, flags=0):将Series/Index中出现的Pattern/regex替换为其他字符串。相当于str.replace()re.sub()

这篇关于 pandas 串替换管子字符不起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆