TugRulz
TugRulz

Reputation: 65

Increasing values in a numpy matrix that are below a certain indice

I'm trying to calculate a cumulative probability counting using 2D numpy matrices. When an object has value x for x-axis and y for y-axis, I add to the cells which has an index less than or equal to (x,y)

i.e. the object has 1,1 in a 3x3 index cell. The matrix should look like this:

[1][1][0]
[1][1][0]
[0][0][0]

The problem is, I cannot do it by simply indexing like matrix[:1][:1].

If possible. I do not want to switch to other library than numpy because it requires too many work. Is there any pythonic way to do it without using daunting for loops?

Upvotes: 0

Views: 31

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53079

You have to do the indexing in one step, i.e [i_expr,j_expr] not [i_expr][j_expr]. (The [][] form only works for scalar indices and even there is bad style.) You also have to add 1 if you want to include the boundaries.

>>> bins = np.zeros((5, 5), int)
>>> i, j = 1, 1
>>> bins[:i+1, :j+1] += 1
>>> bins
array([[1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

Upvotes: 3

Related Questions