Reputation: 6587
How can I avoid the for loop in this numpy operation and create one single array as output that looks as follows:
import numpy as np
c=(np.random.rand(12,5)*12).round()
for n in np.arange(12):
print (np.sum(c==n, axis=1))
It's important that everything stays in numpy as speed is of great importance.
Upvotes: 0
Views: 685
Reputation: 23637
You can avoid the for loop by bringing the [0..12[ range into a shape that broadcasts to the correct output:
import numpy as np
c = (np.random.rand(12, 5) * 12).round()
a = np.arange(12).reshape(12, 1, 1)
out = np.sum(c==a, axis=-1)
print(out)
Note that c==a
creates a temporary boolean array of shape (12, 12, 5)
. Keep this in mind if memory is an issue.
Upvotes: 3
Reputation: 2916
try:
import numpy as np
c = (np.random.rand(12 ,5) * 12).round()
arange_nd = np.empty((12, 12, 5))
for i in range(12):
arange_nd[i] = np.ones((12, 5)) * i
output = (c == arange_nd).sum(axis=2)
the array output
is your printed result
For loop is only in the creation of the array arange_nd
and not on the computation.
Upvotes: -1