Length of each string in a NumPy array

Is there a built-in operation in NumPy that returns the length of each string in an array?

I don't think any of the NumPy string operations do this, is it correct?

I can do this with a loop for

, but maybe something more efficient?

import numpy as np
arr = np.array(['Hello', 'foo', 'and', 'whatsoever'], dtype='S256')

sizes = []
for i in arr:
    sizes.append(len(i))

print(sizes)
[5, 3, 3, 10]

      

+3


source to share


2 answers


You can use vectorize

for numpy

. It's much faster.



mylen = np.vectorize(len)
print mylen(arr)

      

+11


source


For me this would be the path:



sizes = [len(i) for i in arr]

      

+2


source







All Articles