Prevent strings being truncated when replacing values in a numpy array

前端 未结 3 689
半阙折子戏
半阙折子戏 2021-01-07 12:24

Lets say I have arrays a and b

a = np.array([1,2,3])
b = np.array([\'red\',\'red\',\'red\'])

If I were to apply s

3条回答
  •  清歌不尽
    2021-01-07 12:40

    If you construct such array, the type looks like:

    >>> b
    array(['red', 'red', 'red'], dtype=')

    This means that the strings have a length of at most 3 characters. In case you assign longer strings, these strings are truncated.

    You can change the data type to make the maximum length longer, for example:

    b2 = b.astype('

    So now we have an array that can store strings up to 10 characters. Note however that if you make the maximum length larger, the size of the matrix will increase.

提交回复
热议问题