Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
  1. Each element of the array is a coordinate (x, y).
  2. Each coordinate has two labels.

Goal: sum the elements that have the same two labels.

How can this be faster?

>>> import numpy
>>> from scipy import ndimage
>>>
>>> lable1 = numpy.array([0,0,1,1,2,2])
>>> kinds_of_lable1 = 3
>>> 
>>> lable2 = numpy.array([0,1,0,0,1,1])
>>> kinds_of_lable2 = 2
>>> 
>>> data = numpy.array( [ [1, 2], [3,8], [4,5], [2,9], [1, 3], [7, 2] ] )
>>> data_T = data.view().T
>>> 
>>> ### processing ####
... lable1_and_2 = lable1*kinds_of_lable2 + lable2
>>> 
>>> result = numpy.empty( (kinds_of_lable1 * kinds_of_lable2, 2) )
>>> result_T = result.view().T
>>> 
>>> result_T[0] = ndimage.measurements.sum( position.T[0], labels = lable1_and_2, index = range(kinds_of_lable1 * kinds_of_lable2) )
>>> result_T[1] = ndimage.measurements.sum( position.T[1], labels = lable1_and_2, index = range(kinds_of_lable1 * kinds_of_lable2) )
>>> 
>>> ### output ###
... print(result)
[[  3.   4.]
 [  1.   2.]
 [  8.  15.]
 [  0.   0.]
 [  0.   0.]
 [  1.   6.]]
share|improve this question
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.