首页 > 解决方案 > 正则表达式将数据框字符串拆分为python中的列

问题描述

我是正则表达式的新手。我必须使用正则表达式根据模式将数据框行拆分为 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

标签: regexpython-3.xpandas

解决方案


您可以使用

r'(?P<String_Name>.*?)\s*(?P<START_DATE>\d{1,2}/\d{1,2}/\d{2,4})\sto\s+(?P<stop_date>.*)'

请参阅正则表达式演示。正则图:

在此处输入图像描述

熊猫测试:

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

推荐阅读