How is the “along a certain axis” operation implemented?

I can sum all elements along a specific axis using numpy.sum , i.e.

 >>> a = numpy.array([[1,2], [3,4]]) >>> numpy.sum(a, 1) array([3, 7]) 

This is sum along row , which adds the elements of each column one by one.

If there are only 2 or 3 axes, I can implement it using if...elif or swith...case in C / C ++, but what if there are 100 axes? How to implement it?

+4
source share
1 answer

Numpy arrays are just one-dimensional C arrays under the hood, so moving along a single axis is done by going through the C array in steps, the step size depending on what measurement you take (the smallest steps for the fastest dimension that will be in Python / C last measurement).

So, you will need to calculate the step corresponding to the axis, and then go through the array when calculating the sum. For each sum, you start with an offset in the array (the first will be 0), which increases with another step size.

If you want to know a little more, you can read Chapter 15 (you don’t need to read all the previous ones) of the numpy manual , which begins with a section on iterating the numpy array, as done in C.

+2
source

Source: https://habr.com/ru/post/1488243/


All Articles