NumPy中数组的字符串预分配

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

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

有没有可能解决这个问题?

2个回答

6

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

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

但是这样你就失去了拥有一个分配的连续内存块的性能优势,所以最好使用Python列表。 - robince

2

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接