【发布时间】:2019-08-27 19:02:00
【问题描述】:
import pandas as pd
dataframe = pd.DataFrame({'Data' : ['The **ALI**1929 for 90 days but not 77731929 ',
'For all **ALI**1952 28A 177945 ',
'But the **ALI**1914 and **ALI**1903 1912',],
'ID': [1,2,3]
})
Data ID
0 The **ALI**1929 for 90 days but not 77731929 1
1 For all **ALI**1952 28A 177945 2
2 But the **ALI**1914 and **ALI**1903 1912 3
我的数据框看起来像我上面的。我的目标是用与**ALI** 关联的1929 或以下的任何数字替换单词OLDER。所以**ALI**1929 将是**ALI**OLDER 和ALI**1903 也将是**ALI**OLDER 但**ALI**1952 将保持不变。来自How to extract certain length of numbers from a string in python?我试过了
dataframe['older'] = dataframe['Data'].str.replace(r'(?<!\d)(\d{3})(?!\d)', 'OLDER')
但这对我想要的效果不太好。我想要这样的输出
Data ID older
0 The ALI**OLDER for 90 days but not 77731929
1 For all ALI**1952 28A 177945
2 But the ALI**OLDER and ALI**OLDER 1912
如何更改我的正则表达式 str.replace(r'(?<!\d)(\d{3})(?!\d)' 来做到这一点?
【问题讨论】:
-
用你的正则表达式它也会匹配
1912,你想要替换的数字总是在*前面吗? -
是的,它们前面总是有
* -
检查
this这是您要找的吗? -
看起来完全正确
标签: regex python-3.x string pandas replace