regex - 正则表达式将数据框字符串拆分为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
解决方案
您可以使用
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
推荐阅读
- c# - 如何列出用户及其评论
- flutter - Flutter - ParentDataWidget 的错误使用
- sql-server - 将字符串中的时间转换为小时数
- python - 检查 Python 中的文本文件是否为空
- java - Hibernate 为每个数据库更新添加 UTC 偏移量
- javascript - 如何确保某个脚本标签保持在顶部
- r - 如何使用 lubridate 为缺失的参与者数据创建行(纵向研究)?
- amazon-web-services - Terraform AWS EKS 集群部署错误
- php - 在 PHP 中创建基于光标的分页系统
- swiftui - 两个 NavigationBar 项在第二个当前视图中出现两次