Replace values of a numpy index array with values of a list

后端 未结 6 834
迷失自我
迷失自我 2020-12-15 04:31

Suppose you have a numpy array and a list:

>>> a = np.array([1,2,2,1]).reshape(2,2)
>>> a
array([[1, 2],
       [2, 1]])
>>> b = [         


        
6条回答
  •  太阳男子
    2020-12-15 05:09

    You can also use np.choose(idx, vals), where idx is an array of indices that indicate which value of vals should be put in their place. The indices must be 0-based, though. Also make sure that idx has an integer datatype. So you would only need to do:

    np.choose(a.astype(np.int32) - 1, b)
    

提交回复
热议问题