Prevent strings being truncated when replacing values in a numpy array

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

    A marginal improvement on your current approach (which is potentially very wasteful in space):

    import numpy as np
    
    a = np.array([1,2,3])
    b = np.array(['red','red','red'])
    
    replacement = "blue"
    b = b.astype('

    This accounts for strings already in the array, so the allocated space only increases if the replacement is longer than all existing strings in the array.

提交回复
热议问题