4

I'm interested in the multi-dimensional case of Increment Numpy array with repeated indices.

I have an N-dimensional array and a set N index arrays, who's values I want to increment. The index arrays might have have repeated entries.

Without repeats, the solution is

a = arange(24).reshape(2,3,4)
i = array([0,0,1])
j = array([0,1,1])
k = array([0,0,3])
a[i,j,k] += 1

With repeats, (ex. j=array([0,0,2]) ), I'm unable to make numpy increment the replicates.

2 Answers 2

4

How about this:

import numpy as np
a = np.zeros((2,3,4))
i = np.array([0,0,1])
j = np.array([0,0,1])
k = np.array([0,0,3])

ijk = np.vstack((i,j,k)).T
H,edge = np.histogramdd(ijk,bins=a.shape)
a += H  
Sign up to request clarification or add additional context in comments.

1 Comment

I'm using this with cubic bins and flatten cubes of the same size for i,j and k. Any idea why it starts to break down on arrays larger than 27x27x27?
0

I don't know if there is an easier solution with direct array indexing, but this works:

for x,y,z in zip(i,j,k):
    a[x,y,z] +=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.