Comparing strings in Numpy

In the following example

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) 

The comparison is not performed due to a space. Is there a built-in Numpy function that does the equivalent

 In [12]: np.array([x.strip()=='hello' for x in strings]) Out[12]: array([ True, False], dtype=bool) 

which gives the correct result?

+4
source share
1 answer

Numpy provides vectorized string operations for arrays similar to Python string methods. They are in the numpy.char module.

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] 

Hope this will be helpful.

+10
source

Source: https://habr.com/ru/post/1304898/


All Articles