我有一个数据框“数据”,我想用任何内容替换给定列中的所有标点符号(所以我想删除它们)。
在使用神经网络之前,我使用 Python 3、Pandas 和 Numpy 预先格式化一些文本。
symbols = "!\"#$%&()*+-./:;<=>?@[\]^_`{|}~\n"
dataClean = data['description']
for i in symbols:
dataClean = np.char.replace(dataClean,i,"")
我预计,对于 dataClean 中的每个项目(从 0 到 2549),每行中包含的每个字符串都会被删除。 但我得到了返回:
TypeError Traceback (most recent call last)
<ipython-input-87-aa944ae6e61c> in <module>
3
4 for i in symbols:
----> 5 dataClean = np.char.replace(dataClean,i,"")
6
7 print(dataClean[2])
~\Anaconda3\lib\site-packages\numpy\core\defchararray.py in replace(a, old, new, count)
1184 return _to_string_or_unicode_array(
1185 _vec_string(
-> 1186 a, object_, 'replace', [old, new] + _clean_args(count)))
1187
1188
TypeError: string operation on non-string array
最佳答案
如果dataClean
是Pandas系列字符串,您可以使用Series.str.translate
方法:
symbols = "!\"#$%&()*+-./:;<=>?@[\]^_`{|}~\n"
dataClean = data['description']
dataClean = dataClean.str.translate({ord(symbol):"" for symbol in symbols})
例如,假设我们有 DataFrame,df
:
In [59]: df = pd.DataFrame({'data':['[Yes?]', '(No!)', 100]}); df
Out[59]:
data
0 [Yes?]
1 (No!)
2 100
然后我们可以做一个dict将 unicode 序数映射到字符串(或者在本例中为空字符串):
In [52]: symbols = "!\"#$%&()*+-./:;<=>?@[\]^_`{|}~\n"
In [57]: {ord(symbol):"" for symbol in symbols}
Out[57]:
{33: '',
34: '',
...
126: '',
10: ''}
每个 unicode 序数,或 code point它对应于一个 unicode 字符。
Python3 字符串是 unicode 字符序列。对于系列中的每个字符串,translate
方法会将字符串中的每个字符替换为字典映射给出的相应字符串。
In [60]: df['data'].str.translate({ord(symbol):"" for symbol in symbols})
Out[60]:
0 Yes
1 No
2 NaN
Name: data, dtype: object
请注意,translate
将非字符串(例如第三行中的 100
)映射为 NaN
。
关于python - 在 Python 中替换字符会返回 TypeError : string operation on non-string array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747193/