正则表达式将数据帧字符串拆分为python中的列

问题描述 投票:1回答:1

我是正则表达的新手。我必须使用正则表达式根据模式将数据帧行拆分为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
regex python-3.x pandas
1个回答
0
投票

你可以用

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图:

enter image description here

熊猫测试:

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
© www.soinside.com 2019 - 2024. All rights reserved.