2

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 Answer 1

5

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.