Numpy中的字符串比较

2024-09-29 01:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的例子中

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)

哪个结果正确?


Tags: inimportnumpyfalsehelloworldasnp
1条回答
网友
1楼 · 发布于 2024-09-29 01:26:55

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]

希望这对你有帮助。

相关问题 更多 >