python - 如何在 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
解决方案
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
推荐阅读
- php - 找不到路由时如何在 Debian 服务器上发布 Laravel 项目?
- python-3.x - Python3 - ValueError:没有足够的值来解包(预期 3,得到 2)
- python - Django form.is_valid() 每次都返回 false
- python - 准确率停留在 50% Keras
- javascript - 与 NodeJS 和 Webpack 反应 - 捆绑的 js 大文件大小
- android - 将值从活动传递到接口方法并在片段android中检索时出现NullPointer异常
- java - While 循环按预期多执行一次
- laravel - 码头工人。在卷中创建卷
- mysql - 加快sql INNER JOIN和LEFT JOIN组合语句
- azure - Azure 自动化:存储凭据的最佳方式?