0

I have now a fixed-size string numpy array:

import numpy as np

str_arr = np.array(['test1', 'test2'], dtype='<U5')
str_arr[0] = 'longer_string'
print(str_arr)

And it returns

['longe' 'test2']

I'd like to remove this limit. Would there be a way to do so? Below is an example of my failed attempt:

str_arr_copy = str_arr.astype(str)
str_arr_copy[0] = 'longer_string'
print(str_arr_copy)

And it doesn't help at all.

Thank you!

1
  • str_arr.astype('U100') gives you more space, but doesn't eliminate the limit. For this work a regular list is probably better. Commented Apr 11, 2017 at 21:44

1 Answer 1

2

You could convert it to dtype=object, do the assignment, and then convert back to dtype=str:

>>> str_arr_copy = str_arr.astype(object)
>>> str_arr_copy[0] = 'longer_string'
>>> print(str_arr_copy.astype(str))
array(['longer_string', 'test2'], 
      dtype='<U13')
Sign up to request clarification or add additional context in comments.

1 Comment

Using arr.tolist() to generate the intermediate copy runs in about the same time.

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.