在Numpy中进行字符串比较

5
在下面的例子中
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]
希望这对你有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接