代码之家  ›  专栏  ›  技术社区  ›  Boris Gorelik

numpy.array中的字符串预分配

  •  2
  • Boris Gorelik  · 技术社区  · 15 年前
    >>> import numpy as np
    >>> a = np.array(['zero', 'one', 'two', 'three'])
    >>> a[1] = 'thirteen'
    >>> print a
    ['zero' 'thirt' 'two' 'three']
    >>>
    

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

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

    2 回复  |  直到 15 年前
        1
  •  5
  •   Paul    15 年前

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

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

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