python-3.x - 从 Python 中一列的开头和结尾删除空格和标点符号(括号除外)
问题描述
给定一个小数据集如下:
df = pd.DataFrame({'text':[' a..b?!??', '%hgh&12','abc123(bj)!!!', '$$$1234(gz)']})
df
出去:
text
0 a..b?!??
1 %hgh&12
2 abc123(bj)!!!
3 $$$1234(gz)
我需要从列的左侧和右侧删除空格、标点符号,英文和中文括号除外。text
预期结果:
text
0 a..b
1 hgh&12
2 abc123(bj)
3 1234(gz)
我怎么能在 Python 中做到这一点?
我的代码:
df['text'] = df['text'].str.replace('[^\w\s]','')
出去:
0 ab
1 hgh12
2 abc123bj
3 1234gz
Name: text, dtype: object
谢谢。
解决方案
我认为您需要使用不带括号Series.str.strip
的所有值,string.punctuation
并且还添加了
:
df['text'] = df['text'].str.strip('!"#$%&*+,-./:;<=>?@[\]^_`{|}~ ' + "'")
print (df)
text
0 a..b
1 hgh&12
2 abc123(bj)
3 1234(gz)
动态解决方案应该是:
import string
rem = ['(',')']
add = [' ']
a = set(list(string.punctuation) + add) - set(rem)
df['text'] = df['text'].str.strip(''.join(a))
推荐阅读
- python - 从 pandas 列中的 datetime.datetime 中删除时间
- python - 使用输入管道访问图中的输入变量
- ios - 收货日期与沙盒持续时间不匹配
- python-3.x - 从 sklearn 内核密度估计中采样
- javascript - 具有不规则数据的多系列工具提示
- sql-server - 参数化动态 sql 查询 (VB.Net)
- python - 在没有在 python 中运行函数的情况下检查了 nonlocal 语句
- c# - How to include the name of the file at the end of the string
- java - 如何运行 Jimple 文件?
- php - PDO 和 MSSQL,如何设置 utf8 字符集?