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
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