Extract first n characters from each element of a numpy string array

Viewed 831

I have a NumPy array which elements are strings. For example

import numpy as np    
a = np.array(["abcde", "degag"])

I need to extract the first n characters from each element of the array (substr/strleft). The result for the first 3 characters should be an aray like this one:

array(['abc', 'deg'], dtype='<U3')

Thank you very much

1 Answers

It's almost staring you in the face:

In [93]: a = np.array(["abcde", "degag"])
In [94]: a.astype('U3')
Out[94]: array(['abc', 'deg'], dtype='<U3')

otherwise you have to iterate

In [95]: [s[:3] for s in a]
Out[95]: ['abc', 'deg']
Related