python - Numpy 中的字符串比较

标签 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)

由于空白,比较失败。是否有一个 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/

相关文章:

python - 使用 matplotlib.animation 从 matplotlib 制作视频后创建的空 .mp4 文件

python - Variable.get ('x' , deserialize_json=True) 与 Jinja '{{ var.json.x }}' 相同吗?

python - 为什么 .sum() 比 .any() 或 .max() 快?

Python Selenium,单击复选框

python - 遗传算法如何在不知道搜索量的情况下优化神经网络的权重?

python - 使用 numpy 进行多处理使 Python 在 OSX 上意外退出

python - 导入错误 : cannot import name '_validate_lengths'

python - 在 Python 的 scipy/numpy 中有效地找到非零区间?

python - 网站/应用程序大小

python - 将成员添加到 Python 枚举