Sum elements of an array from given labels, in python, without for loop
‘For loops’ are slow in python.
That’s why it’s better to use numpy or scipy functions.
Here a simple example on how to sum given element of b given the index a of c:
Now some benchmarks:
Initialization of the arrays:
First the code with ‘for loop’:
And now the code without ‘for loop’:
And the result is the same:
out: True
Now we’ll benchmark the execution time, with the loop for 10 to 100 iterations in the loop:
And without the loop:
And the result shows an obvious advantage to use the scipy function when the number of iterations is more than 50:
If you want to ask me a question or leave me a message add @bougui505 in your comment.