numpy.arrays中的字符串预分配

时间:2009-11-23 14:16:15

标签: python numpy

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

如您所见,第二个元素已被截断为原始数组中的最大字符数。

是否可以解决此问题?

2 个答案:

答案 0 :(得分:5)

如果您不知道最大长度元素,则可以使用dtype = object

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

答案 1 :(得分:2)

使用dtype中的numpy.array参数,例如:

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