Nickpick
Nickpick

Reputation: 6587

How to avoid for loop in numpy

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

Answers (2)

MB-F
MB-F

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

Francesco Nazzaro
Francesco Nazzaro

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

Related Questions