简体   繁体   中英

Remove the fixed-size constraint in numpy fixed-size array

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!

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM