0

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.

1
  • How is the print command in the loop related to the single array you want as output? Commented Feb 24, 2016 at 8:55

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That is correct, but it seems I made a mistake in asking the question. The top left element of the result should tell me how many times a '0' occurs in row 0. The bottom right should show many how many '11' there are in the last row. Any suggestions what I need to change?
-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.