Numpy中的字符串比较

ast*_*rog 5 python numpy

在以下示例中

In [8]: import numpy as np

In [9]: strings = np.array(['hello    ', 'world    '], dtype='|S10')

In [10]: strings == 'hello'
Out[10]: array([False, False], dtype=bool)
Run Code Online (Sandbox Code Playgroud)

由于空白,比较失败.是否有一个Numpy内置函数,相当于

In [12]: np.array([x.strip()=='hello' for x in strings])
Out[12]: array([ True, False], dtype=bool)
Run Code Online (Sandbox Code Playgroud)

哪个给出了正确的结果?

Gar*_*err 11

Numpy为类似Python的字符串方法的数组提供矢量化字符串操作.它们位于numpy.char模块中.

http://docs.scipy.org/doc/numpy/reference/routines.char.html

import numpy as np

strings = np.array(['hello    ', 'world    '], dtype='|S10')

print np.char.strip(strings) == 'hello'
# prints [ True False]
Run Code Online (Sandbox Code Playgroud)

希望这是有帮助的.