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)
比较失败是因为有空格的原因。有没有Numpy的内置函数可以做到和下面这个一样的效果
In [12]: np.array([x.strip()=='hello' for x in strings])
Out[12]: array([ True, False], dtype=bool)
而且能给出正确的结果呢?
1 个回答
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]
希望这对你有帮助。