代码之家  ›  专栏  ›  技术社区  ›  levant pied

从坐标和[duplicate]构建numpy数组的最快方法

  •  0
  • levant pied  · 技术社区  · 6 年前

    (row, col) 坐标,例如:

    [(0, 0), (1, 1), (0, 0)]
    

    2 0
    0 1
    

    计算列出的每个坐标并将其放置在数组中的正确位置。即。 (0, 0) a[0, 0] == 2

    另外,是否有类似reduce的功能?例如,do new = f(acc, el) new = acc + el .

    2 回复  |  直到 6 年前
        1
  •  3
  •   Paul Panzer    6 年前

    np.bincount .

    >>> import numpy as np                                                   
    >>>                                                                                                                 
    >>> coords = [(0, 0), (1, 1), (0, 0)]                                       
    >>> 
    >>> shp = np.max(coords, axis=0) + 1     
    >>> flt = np.ravel_multi_index(np.moveaxis(coords, -1, 0), shp)               
    >>> result = np.bincount(flt, minlength=shp.prod()).reshape(shp)                         
    >>>                                                                                                                 
    >>> result                                                                                                          
    array([[2, 0],                                                                                                      
           [0, 1]])                                                                                                     
    

    正如@MikeMiller所指出的 moveaxis 在这里是过度杀戮; np.transpose(coords) 或者坐标恰好是一个数组 coords.T 移动轴 coords 因为某种原因 2D

        2
  •  2
  •   today    6 年前

    使用 np.unique() 计算唯一坐标的数目( 但是,我不知道这是不是最快的方法 ,则不是,请参见下面的计时):

    import numpy as np
    
    a = [(0,0), (1,1), (1,0), (0,0)]
    
    b = np.array(a)
    u, c = np.unique(b, axis=0, return_counts=True)
    m = np.max(b)+1
    ans = np.zeros((m, m))
    ans[u[:,0], u[:,1]] = c
    
    # ans
    array([[ 2.,  0.],
           [ 1.,  1.]])
    

    我做了一些计时:

    # data preparation
    max_coord = 10000
    max_size = 100000
    
    # this is awful, I know it can be done much better...
    coords = [(int(np.random.randint(max_coord, size=1)),
               int(np.random.randint(max_coord, size=1))) for _ in range(max_size)]
    
    # timings using %timeit
    
    # my solution
    139 ms ± 592 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    # Paul Panzer's solution
    142 ms ± 461 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    # with max_size = 1000000
    # my solution
    827 ms ± 19.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    # Paul's solution
    748 ms ± 4.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    几乎一样(虽然我不知道他们的记忆足迹;具有 max_size=1000000 max_coord=100000 两种解决方案都给出 MemoryError