Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String preallocation in numpy.arrays

Tags:

python

numpy

>>> import numpy as np
>>> a = np.array(['zero', 'one', 'two', 'three'])
>>> a[1] = 'thirteen'
>>> print a
['zero' 'thirt' 'two' 'three']
>>>

As you can see, the second element has been truncated to the maximum number of characters in the original array.

Is it possible to workaround this problem?

like image 480
Boris Gorelik Avatar asked Jul 27 '26 16:07

Boris Gorelik


1 Answers

If you don't know the maximum length element, then you can use dtype=object

>>> import numpy as np
>>> a = np.array(['zero', 'one', 'two', 'three'], dtype=object)
>>> a[1] = 'thirteen'
>>> print a
['zero' 'thirteen' 'two' 'three']
>>>
like image 69
Paul Avatar answered Jul 30 '26 04:07

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!