user3297266
user3297266

Reputation: 45

Adding to an existing element in numpy array?

How do you add one (+1) to a cell with an existing element in an numpy array? I have a 21x23 zeros array and I want to count occurences by adding one .

for r in holdscore:
    results = np.zeros(shape=(21, 23))
    if one_game(r) < 21:
        results[r,one_game(r)] += 1
    if one_game(r) > 21:
        results[r, 22] += 1    

Upvotes: 0

Views: 147

Answers (1)

user2357112
user2357112

Reputation: 280182

You're incrementing correctly. The problem is that you forget about the old array and make a new one every time through the loop.

Move this statement:

results = np.zeros(shape=(21, 23))

outside the loop:

results = np.zeros(shape=(21, 23))
for r in holdscore:
    if one_game(r) < 21:
        results[r,one_game(r)] += 1
    if one_game(r) > 21:
        results[r, 22] += 1

so it doesn't happen on every iteration.

Upvotes: 2

Related Questions