Fastest way to convert a list of indices to 2D numpy array of ones

前端 未结 6 1548
星月不相逢
星月不相逢 2021-01-05 15:11

I have a list of indices

a = [
  [1,2,4],
  [0,2,3],
  [1,3,4],
  [0,2]]

What\'s the fastest way to convert this to a numpy array of ones,

6条回答
  •  不知归路
    2021-01-05 15:51

    This might not be the fastest way. You will need to compare execution times of these answers using large arrays in order to find out the fastest way. Here's my solution

    output = np.zeros((4,5))
    for i, ix in enumerate(a):
        output[i][ix] = 1
    
    # output -> 
    #   array([[0, 1, 1, 0, 1],
    #   [1, 0, 1, 1, 0],
    #   [0, 1, 0, 1, 1],
    #   [1, 0, 1, 0, 0]])
    

提交回复
热议问题