我是正则表达的新手。我必须使用正则表达式根据模式将数据帧行拆分为3列。
数据框中的示例行:
"Sample String(just a / string) 04/04/2014 to ongoing"
我正在尝试低于正则表达但不工作:
pat = re.compile("(?P<String_Name>[a-zA-Z- )(/ ]*)(?P<START_DATE>\d{1,2}/\d{1,2}/\d{2,4})(?P<stop_date>[a-zA-Z]*)?")
df=new_df.text.str.extract(pat)
需要像这样的输出:
String_Name = Sample String(just a / string)
Start_Date = 04/04/2014
Stop_Date = ongoing
你可以用
r'(?P<String_Name>.*?)\s*(?P<START_DATE>\d{1,2}/\d{1,2}/\d{2,4})\sto\s+(?P<stop_date>.*)'
见regex demo。 Regulex图:
熊猫测试:
df = pd.DataFrame({'text':['Sample String(just a / string) 04/04/2014 to ongoing']})
rx = r'(?P<String_Name>.*?)\s*(?P<START_DATE>\d{1,2}/\d{1,2}/\d{2,4})\sto\s+(?P<stop_date>.*)'
df1 = df['text'].str.extract(rx)
输出:
>>> df1
String_Name START_DATE stop_date
0 Sample String(just a / string) 04/04/2014 ongoing