【问题标题】:Remove specific characters from a pandas column?从熊猫列中删除特定字符?
【发布时间】:2020-02-13 17:47:36
【问题描述】:

您好,我有一个数据框,我想从以它开头的每一行中删除一组特定的字符“fwd”。我面临的问题是我用来执行此操作的代码正在删除以字母“f”开头的任何内容。

我的数据框如下所示:

  summary 
0 Fwd: Please look at the attached documents and take action 
1 NSN for the ones who care
2 News for all team members 
3 Fwd: Please take action on the action needed items 
4 Fix all the mistakes please 

当我使用代码时:

df['Clean Summary'] =  individual_receivers['summary'].map(lambda x: x.lstrip('Fwd:'))

我最终得到一个如下所示的数据框:

      summary 
0 Please look at the attached documents and take action 
1 NSN for the ones who care
2 News for all team members 
3 Please take action on the action needed items 
4 ix all the mistakes please 

我不希望最后一行在“修复”中丢失 F。

【问题讨论】:

  • 这将删除以字母“f”开头的所有内容这是意料之中的,请查看str.lstrip() 的文档。
  • 这能回答你的问题吗? Strip removing more characters than expected
  • 是的,我明白了,有没有更好的方法来专门删除仅使用 'fwd:' 的案例
  • Regex 可能是你最好的选择。
  • 另一个选项是:individual_receivers['summary'].str.lstrip('Fwd:').where(individual_receivers['summary'].str.startswith('Fwd:'),individual_receivers['summary'])

标签: python pandas strip


【解决方案1】:

你应该使用regex记住^表示开头:

df['Clean Summary'] = df['Summary'].str.replace('^Fwd','')

这是一个例子:

df = pd.DataFrame({'msg':['Fwd: o','oe','Fwd: oj'],'B':[1,2,3]})
df['clean_msg'] = df['msg'].str.replace(r'^Fwd: ','')
print(df)

输出:

       msg  B clean_msg
0   Fwd: o  1         o
1       oe  2        oe
2  Fwd: oj  3        oj

【讨论】:

  • 你测试了吗? \b 不是这个词的开头吗?
  • 这有效并且有帮助,但我还有一个问题,是否有一些要删除的短语列表而不是一个单独的短语?
  • 当然,正则表达式接受你可以使用的模式。您可以尝试针对该问题提出另一个问题,以便我们解决这个问题。将问题的链接作为评论发布,以便我看到它,谢谢!
【解决方案2】:

你不仅失去了'F',还失去了'w''d'':'This is the way lstrip works - 它删除了传递字符串中的所有字符组合。

你实际上应该使用x.replace('Fwd:', '', 1)

1 - 确保仅删除第一次出现的字符串。

【讨论】:

  • 如果Fwd:不是在开头?
猜你喜欢
  • 2017-10-01
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 2021-09-25
  • 2016-10-21
  • 2017-07-27
  • 2019-10-01
相关资源
最近更新 更多