使用Canopy和Pandas,我有数据框a,其定义如下:
a=pd.read_csv('text.txt')
df=pd.DataFrame(a)
df.columns=["test"]
test.txt是一个单列文件,其中包含一个包含文本,数字和标点符号的字符串列表。
假设df看起来像:
测试
%HGH&安培; 12
ABC123 !!!
porkyfries
我希望我的结果是:
测试
hgh12
ABC123
porkyfries
到目前为止的努力:
from string import punctuation /-- import punctuation list from python itself
a=pd.read_csv('text.txt')
df=pd.DataFrame(a)
df.columns=["test"] /-- define the dataframe
for p in list(punctuation):
...: df2=df.med.str.replace(p,'')
...: df2=pd.DataFrame(df2);
...: df2
上面的命令基本上只返回相同的数据集。 感谢任何线索。
编辑:我使用Pandas的原因是因为数据很大,跨越了大约1M行,未来的编码使用将应用于最多30M行的列表。 简而言之,我需要以非常有效的方式为大数据集清理数据。
答案 0 :(得分:5)
使用正确的正则表达式replace
会更容易:
In [41]:
import pandas as pd
pd.set_option('display.notebook_repr_html', False)
df = pd.DataFrame({'text':['test','%hgh&12','abc123!!!','porkyfries']})
df
Out[41]:
text
0 test
1 %hgh&12
2 abc123!!!
3 porkyfries
[4 rows x 1 columns]
使用正则表达式,而不是字母数字/空白
In [49]:
df['text'] = df['text'].str.replace('[^\w\s]','')
df
Out[49]:
text
0 test
1 hgh12
2 abc123
3 porkyfries
[4 rows x 1 columns]
答案 1 :(得分:3)
用于从dataframme中的文本列中删除标点符号:
在:
import re
import string
rem = string.punctuation
pattern = r"[{}]".format(rem)
pattern
输出:
'[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]'
在:
df = pd.DataFrame({'text':['book...regh', 'book...', 'boo,', 'book. ', 'ball, ', 'ballnroll"', '"rope"', 'rick % ']})
df
输出:
text
0 book...regh
1 book...
2 boo,
3 book.
4 ball,
5 ballnroll"
6 "rope"
7 rick %
在:
df['text'] = df['text'].str.replace(pattern, '')
df
您可以用所需的角色替换图案。前 - 替换(模式,'$')
输出:
text
0 bookregh
1 book
2 boo
3 book
4 ball
5 ballnroll
6 rope
7 rick
答案 2 :(得分:1)
翻译通常被认为是删除标点符号的最简洁,最快捷的方法(source)
import string
text = text.translate(None, string.punctuation.translate(None, '"'))
你可能会发现在将它加载到pandas之前删除'a'中的标点符号会更好。