在下面的例子中
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)
哪个给出了正确的结果?
最佳答案
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]
希望对您有所帮助。
关于python - Numpy 中的字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2501362/