rpb
rpb

Reputation: 3299

Count all values in a 2D matrix greater than a value for a 3D array

Given a 3D arr

np.random.seed(0)
arr=np.random.rand(4,3,3)

The arr is a below

0.54881,0.71519,0.60276
0.54488,0.42365,0.64589
0.43759,0.89177,0.96366


0.38344,0.79173,0.52889
0.56804,0.92560,0.07104
0.08713,0.02022,0.83262

0.77816,0.87001,0.97862
0.79916,0.46148,0.78053
0.11827,0.63992,0.14335


0.94467,0.52185,0.41466
0.26456,0.77423,0.45615
0.56843,0.01879,0.61764

I would like to calculate total cell that greater than 0.7 at the last two axis.

Which should give the answer of

3,3,5,2

Extension from the suggestion made from this OP, I reckon this can be achieved as below

[(darr>0.7).sum() for darr in arr]

But, I wonder, whether there is another approach to avoid the list comprehension.

Upvotes: 0

Views: 267

Answers (1)

rchome
rchome

Reputation: 2723

You can sum over multiple axes.

(arr > 0.7).sum(axis=(1, 2))
array([3, 3, 5, 2])

Upvotes: 2

Related Questions