开发者

String preallocation in numpy.arrays

开发者 https://www.devze.com 2022-12-12 01:19 出处:网络
&开发者_运维百科gt;>> import numpy as np >>> a = np.array([\'zero\', \'one\', \'two\', \'three\'])
&开发者_运维百科gt;>> 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?


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


Use the dtype argument in numpy.array, e.g.:

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

精彩评论

暂无评论...
验证码 换一张
取 消