Prevent strings being truncated when replacing values in a numpy array

前端 未结 3 679
半阙折子戏
半阙折子戏 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:39

    You can handle variable length strings by setting the dtype of b to be "object":

    import numpy as np
    a = np.array([1,2,3])
    b = np.array(['red','red','red'], dtype="object")
    
    b[a<3] = "blue"
    
    print(b)
    

    this outputs:

    ['blue' 'blue' 'red']
    

    This dtype will handle strings, or other general Python objects. This also necessarily means that under the hood you'll have a numpy array of pointers, so don't expect the performance you get when using a primitive datatype.

提交回复
热议问题