这里不需要正则表达式.只需使用astype将数组转换为1字节字符串 –
v = np.array(['abc', 'def', 'ghi'])
>>> v.astype('
array(['a', 'd', 'g'],
dtype='
或者,您可以更改其视图和步幅.这是针对等大小字符串的略微优化版本. –
>>> v.view('
array(['a', 'd', 'g'],
dtype='
这是.view方法的更通用版本,但这适用于具有不同长度的字符串数组.感谢Paul Panzer为suggestion –
>>> v.view('
array(['a', 'd', 'g'],
dtype='
性能
y = np.array([x * 20 for x in v]).repeat(100000)
y.shape
(300000,)
len(y[0]) # they're all the same length - `abcabcabc...`
60
现在,时间 –
# `astype` conversion
%timeit y.astype('
100 loops, best of 3: 5.03 ms per loop
# `view` for equal sized string arrays