orudyy
orudyy

Reputation: 115

How to sum application of function to each 3d matrix inside an array?

I have a np.ndarray of 4 dimensions (x, y, z, p) and want to add the results of applying a function over each matrix (y, z, p) inside the x dimension.

What I want to do is something like:

a = np.random.random((4, 12, 10, 100))
collect += np.greater(a, 10)

Thus, collect should have the sum of np.greater(a[0], 10) + np.greater(a[1], 10) + np.greater(a[2], 10) + np.greater(a[3], 10) and shape (12, 10, 100).

Is there a way to do such thing with numpy without an explicit loop traversing all elements inside x dimension?

Upvotes: 1

Views: 75

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114320

The simple solution for adding all the numbers along an axis is of course to add the numbers along that axis:

a = np.random.randint(20, size=(4, 12, 10, 100))
np.sum(a > 10, axis=0)

or more concisely:

(a > 10).sum(0)

There are other ways of doing the same thing. Absolutely massive overkill is the suggestion to use np.einsum on a single array. In this case, you do have to explicitly convert the input to an integer, since einsum does not promote booleans to integers, unlike sum:

np.einsum('ijkl->jkl', (a > 10).astype(int))

The condition np.greater(a, 10) is more intuitive as a > 10, and will always be false for np.random.random, since that generates in the range [0.0, 1.0).

Upvotes: 3

Related Questions