【问题标题】:How to Remove particular changing text in from a DataFrame column in Python?如何从 Python 中的 DataFrame 列中删除特定的更改文本?
【发布时间】:2020-06-10 13:35:03
【问题描述】:

我有一个包含“测试”列的数据框。它看起来像这样:

Column Test 
'[ABC: 814.6] text text text text [text:123]'
'[ABC: 432.9] text text [ABC: 433] text text [text:123]'
'[ABC: 1] text text text [342:] text [text:123]'

我想删除所有 '[ABC: XXX.X]' 部分。 我知道如何替换“静态”文本,如下所示:

df['Test_New'] = df['Test'].str.replace("[ABC: XXX.X]", '')

然而,由于 XXX.X 正在改变,我不知道如何解决这个问题。

期望的输出:

Column Test 
' text text text text [text:123]'
' text text  text text [text:123]'
' text text text [342:] text [text:123]'

提前非常感谢!

【问题讨论】:

  • Str.replace 支持正则表达式。文档中的详细信息

标签: python string dataframe replace python-re


【解决方案1】:

根据@ZaxR 的评论,str.replace 支持正则表达式。

df['Test_New'] = df['Test'].str.replace(r"\[ABC: [\d]{1,3}(?:.\d)?\]", '')

【讨论】:

  • 看起来这行得通!如果我们确实有 2 位小数,你知道是否也有可能让这个工作?例如'[ABC: 751.96]'。非常感谢@ywbaek
  • @Roverflow,你只需要指定df['Test_New'] = df['Test'].str.replace(r"\[ABC: [\d]{1,3}(?:.[\d]{1,2})?\]", '')
猜你喜欢
  • 2012-09-14
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多