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

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

    How about this:

    ncol = 5
    nrow = len(a)
    out = np.zeros((nrow, ncol), int)
    out[np.arange(nrow).repeat([*map(len,a)]), np.concatenate(a)] = 1
    out
    # array([[0, 1, 1, 0, 1],
    #        [1, 0, 1, 1, 0],
    #        [0, 1, 0, 1, 1],
    #        [1, 0, 1, 0, 0]])
    

    Here are timings for a 1000x1000 binary array, note that I use an optimized version of the above, see function pp below:

    pp 21.717635259992676 ms
    ts 37.10938713003998 ms
    u9 37.32933565042913 ms
    

    Code to produce timings:

    import itertools as it
    import numpy as np
    
    def make_data(n,m):
        I,J = np.where(np.random.random((n,m))

提交回复
热议问题