首页 > 解决方案 > 如何在 Pandas 中去除字符串列开头和结尾的标点符号

问题描述

我有一个数据框,其中某些行有不必要的标点符号,例如?. 字符串类型列的开头和结尾等,如何使用 Pandas 去除那些标点符号?谢谢。

id   price    fruits
01     1       .apple
02     2       ,apple, banana?
03     3       ?orange?

应该是这样的

id   price    fruits
01     1       apple
02     2       apple, banana
03     3       orange

标签: pythonpandas

解决方案


str.strip与 一起使用punctuation

import string
df['fruits'] = df['fruits'].str.strip(string.punctuation)
print (df)
   id  price         fruits
0   1      1          apple
1   2      2  apple, banana
2   3      3         orange

print (string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

编辑:

对于自定义punctuation,可以使用字符串,只有"在检查值时才需要转义:

df['fruits'] = df['fruits'].str.strip(",\"?'.")
print (df)

   id  price         fruits
0   1      1          apple
1   2      2  apple, banana
2   3      3         orange

推荐阅读