python - pandas str 中的正则表达式替换以排除部分匹配
问题描述
我正在尝试用 111 替换 'hi' 和 'hello' 但被 pandas.str.replace() 卡住了。有什么建议么?谢谢!
a1 = pd.Series('12:04:25 Roberts: Hi, Hello, hi this hi')
## it will replace 'this' too using the re below
a1.str.replace('(hello|hi)', '111', regex=True, flags=re.IGNORECASE)
-- 12:04:25 Roberts: 111, 111, 111 t111s 111
## if I set '^hi$' then 'Hi' will be keeped
a1.str.replace('(hello|^hi$)', '111', regex=True, flags=re.IGNORECASE)
-- 12:04:25 Roberts: Hi, 111, hi this hi
## taking space and comma into consideration still the same
a1.str.replace('(hello|^\s?hi,?$)', '111', regex=True, flags=re.IGNORECASE)
-- 12:04:25 Roberts: Hi, 111, hi this hi
解决方案
您可以尝试添加一个lookbehind:
>>> a1.str.replace('(?<=\s|,)(hello|hi)', '111', regex=True, flags=re.IGNORECASE)
0 12:04:25 Roberts: 111, 111, 111 this 111
dtype: object
>>>
推荐阅读
- sphinx - 狮身人面像错误: (type='index') 已经存在
- mariadb - MariaDB 为每个 find_in_set 值选择记录
- matrix - 如何使用颤振执行有关缩放,旋转和平移使用矩阵的功能
- c - 在使用诸如 C 之类的编程语言的某些软件中是否有间接寻址的实际应用?
- numpy - 如何根据值标记 numpy 数组?
- python-2.7 - 使用“with”方法在 Python 中保存文件
- android - Android InputType.TYPE_NUMBER_VARIATION_PASSWORD 到可见数字密码(仅限数字)
- r - 是否有一个 R 函数可以替换使用多个数据帧的几列的循环?
- c++ - 在opengl矩形上使用着色器会导致它消失
- php - 使用未定义的常量字符串 - 从变量调用类名时假定为“字符串”