Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of numpy reduceat() in python?

Tags:

python

numpy

I am very new in Python and I read at this moment just the tutorial.

I am confused about the reduceat() function.

I saw the example:

np.add.reduceat([0,1,2,3,4,5,6,7],[0,4,1,5,2,6,3,7])[::2]

and result is:

array([ 6, 10, 14, 18])

How does it come out? Can some one explain for me?

like image 525
xirururu Avatar asked Dec 20 '22 13:12

xirururu


1 Answers

The above answer is right but fails to explain what .reduceat is actually doing! basically it is returning the sum of the elements that lie in the sliced array

for Example:

array = np.arange(10)
indices = np.array([1,3,4,5])
output = numpy.add.reduceat(array,indices)  
print(output)

OUTPUT: [ 3 3 4 35]

What is happening behind the scenes is, it is applying the .reduce() repeatedly over the array like shown below :

print("Step1 : ", np.add.reduce(array[1:3]))
print("Step2 : ", np.add.reduce(array[3:4]))
print("Step3 : ", np.add.reduce(array[4:5]))
print("Step4 : ", np.add.reduce(array[5:]))

and appends the results of each step to a list and displays the result! Hope you understood what actually happens when you call numpy.add.reduceat() function! I am not saying that the above answer is wrong, just providing another explanation to understand the function better! Hope this helps! Thank you!

like image 137
Adarsh_V_Desai Avatar answered Dec 31 '22 20:12

Adarsh_V_Desai