Numpy broadcasting

前端 未结 1 1952
礼貌的吻别
礼貌的吻别 2021-01-23 04:50

The following code gives me how many times the elements in a (0-11) occur in the first row of array c. (a==c[0]). How can I adjust this code so it also does the same for all row

相关标签:
1条回答
  • 2021-01-23 05:49

    If you must use broadcasting that would incur heavy memory usage, you could do -

    (c[...,None] == np.arange(12)).sum(1)
    

    For bigger sized c, a better way would be to not disturb c and just move around np.arange(12), like so -

    (c == (np.arange(12)[:,None,None])).sum(-1).T
    

    Here's some proof on that theory -

    In [28]: c=(np.random.rand(2000,5000)*12).round()
    
    In [29]: %timeit (c[...,None] == np.arange(12)).sum(1)
    1 loops, best of 3: 423 ms per loop
    
    In [30]: %timeit (c == (np.arange(12)[:,None,None])).sum(-1).T
    1 loops, best of 3: 232 ms per loop
    
    0 讨论(0)
提交回复
热议问题