【问题标题】:Stripping out a piece of text string from a column in Python using REGEX使用 REGEX 从 Python 中的列中删除一段文本字符串
【发布时间】:2020-08-24 15:58:54
【问题描述】:

我需要从数据框中的列中删除日期和时间字符串,该列具有不均匀的分隔符行,即一些带有三个逗号和一些带有四个逗号。

我正在使用 Python3,熊猫

例子:

df['sample field'].head(2) 

返回

"4294-Skateboard Foundation (MSF) Advanced Rider Course (ARC) , 1134123 , Oct 24 2016 12:00AM ,"
"1254-Skateboard Foundation (MSF) Experienced Rider Courses (ERC/BRC 2) , 3217121 , May 15 2015 12:00AM ,"
"4457-Total Control, Level 1 (Advanced Skateboarding Clinic) (TCL1) , 6743468 , Nov 11 2013 12:00AM ," 

预期回报

"4294-Skateboard Foundation (MSF) Advanced Rider Course (ARC) 1134123"
"1254-Skateboard Foundation (MSF) Experienced Rider Courses (ERC/BRC 2) 3217121"
"4457-Total Control Level 1 (Advanced Skateboarding Clinic) (TCL1) 6743468" 

 

我试图弄清楚如何去除日期和时间值:在背面,如果将文本字符串放入新列:Intended Returned。

为了做相反的事情,我使用了以下内容:

df3_1['Date'] = df3_1['Course ID'].str.extract('([A-Za-z]+\s+\d+\s+\d+\s+\d+:[0-9A-Z]+(?=\s+\,+))')  

这在去除日期方面非常有效,但我现在正试图找出如何在没有日期的情况下保留文本。

【问题讨论】:

  • 是字符串末尾的逗号吗?我似乎在这里找不到多个分隔符,因为您可以通过 rsplit, 上选择它。如果您共享两行的数据框,并且您的预期输出也采用数据框格式,则更容易

标签: python-3.x regex pandas dataframe split


【解决方案1】:

假设你已经有了日期列

df['Course ID'].replace(regex=r'(?i)'+ df.Date,value="")
0    4457-I only, need, this,  
1      2359-I only need, this, 
Name: Course ID, dtype: object

【讨论】:

  • 嗨 YOBEN,我尝试了这个解决方案,但出现以下错误:TypeError: can only concatenate str (not "DatetimeArray") to str.问题:当我想要做的只是删除日期值时,为什么我要尝试连接空白日期值?
【解决方案2】:
df=pd.DataFrame({'Text':['4457-I only, need, this, Nov 11 2013 12:00AM ,',
                 '2359-I only need, this, Apr 11 2013 12:00AM ,']})

#get rid of the date section and merge the rest on whitespace
df['extract'] = df.Text.str.strip(',').str.split(',').str[:-1].str.join(' ')

df
            Text                                           extract
0   4457-I only, need, this, Nov 11 2013 12:00AM ,  4457-I only need this
1   2359-I only need, this, Apr 11 2013 12:00AM ,   2359-I only need this

【讨论】:

  • 这一项效果很好:“4294-Skateboard Foundation (MSF) Advanced Rider Course (ARC) , 1134123 , Oct 24 2016 12:00AM ” --- 但不是下面的那个 == ==================================================== “1254-Skateboard Foundation (MSF) 经验丰富的骑手课程 (ERC/BRC 2),3217121,2015 年 5 月 15 日上午 12:00,”
  • 这似乎是一个更好的例子。您可以将其添加到您的问题中,并具有预期的输出
  • 点了!谢谢,我编辑了问题以反映更好的情况。
  • 我只是用当前代码运行它,它就像你发布的那样出来。当你运行它时它会返回什么?
  • 有趣。 [:-1] 应该获取字符串并排除最后一个条目。更改为 1 本质上是str[0],这是拆分后的第一个条目。无论如何,希望你能解决问题并更好地理解它。
猜你喜欢
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 2016-08-20
  • 2022-08-19
相关资源
最近更新 更多