从熊猫列中删除特定字符?

时间:2020-02-13 17:47:36

标签: python pandas strip

你好,我有一个数据框,我想从其中开始的每一行中删除一组特定的字符“ 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 

我不希望最后一行丢失'Fix'中的F。

2 个答案:

答案 0 :(得分:2)

您应该使用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

答案 1 :(得分:0)

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

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

1-确保仅删除字符串的第一个匹配项。