np.char 中的大多数(如果不是全部)函数将现有的str 方法应用于数组的每个元素。它比直接迭代(或vectorize)要快一点,但不是那么快。
没有字符串切片器;至少不是那种名字。最接近的是使用切片进行索引:
In [274]: 'astring'[1:3]
Out[274]: 'st'
In [275]: 'astring'.__getitem__
Out[275]: <method-wrapper '__getitem__' of str object at 0xb3866c20>
In [276]: 'astring'.__getitem__(slice(1,4))
Out[276]: 'str'
迭代方法可以使用frompyfunc(vectorize 也使用):
In [277]: a = numpy.array(['hello', 'how', 'are', 'you'])
In [278]: np.frompyfunc(lambda x:x[1:3],1,1)(a)
Out[278]: array(['el', 'ow', 're', 'ou'], dtype=object)
In [279]: np.frompyfunc(lambda x:x[1:3],1,1)(a).astype('U2')
Out[279]:
array(['el', 'ow', 're', 'ou'],
dtype='<U2')
我可以将其视为单个字符数组,然后对其进行切片
In [289]: a.view('U1').reshape(4,-1)[:,1:3]
Out[289]:
array([['e', 'l'],
['o', 'w'],
['r', 'e'],
['o', 'u']],
dtype='<U1')
我仍然需要弄清楚如何将其转换回“U2”。
In [290]: a.view('U1').reshape(4,-1)[:,1:3].copy().view('U2')
Out[290]:
array([['el'],
['ow'],
['re'],
['ou']],
dtype='<U2')
初始查看步骤将数据缓冲区显示为 Py3 字符(这些将是 S 或 Py2 字符串大小写中的字节):
In [284]: a.view('U1')
Out[284]:
array(['h', 'e', 'l', 'l', 'o', 'h', 'o', 'w', '', '', 'a', 'r', 'e', '',
'', 'y', 'o', 'u', '', ''],
dtype='<U1')
选择 1:3 的列相当于选择a.view('U1')[[1,2,6,7,11,12,16,17]],然后再进行整形和查看。在不深入细节的情况下,我对它需要副本并不感到惊讶。