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

前端 未结 6 1590
星月不相逢
星月不相逢 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:49

    May not be the best way but the only way I can think of:

    output = np.zeros((4,5))
    for i, (x, y) in enumerate(zip(a, output)):
        y[x] = 1
        output[i] = y
    print(output)
    

    Which outputs:

    [[ 0.  1.  1.  0.  1.]
     [ 1.  0.  1.  1.  0.]
     [ 0.  1.  0.  1.  1.]
     [ 1.  0.  1.  0.  0.]]
    

提交回复
热议问题