从 pandas 列中删除特定字符?

Remove specific characters from a pandas column?

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

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

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

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