Skip to content
Advertisement

Numpy apply along axis based on row index

Trying to apply numpy inbuilt function apply_along_axis based on row index position

JavaScript

OP:

JavaScript

The function:

JavaScript

Op:

JavaScript

But is there a way to use this function based on row index position for example, if its a even row index then add 10 and if its a odd row index then add 50

Sample:

JavaScript

Advertisement

Answer

When iterating on array, directly or with apply_along_axis, the subarray does not have a .index attribute. So we have to pass an explicit index value to your function:

JavaScript

apply doesn’t have a way to add this index, so instead we have to use an explicit iteration.

JavaScript

replacing // with %

JavaScript

But a better way is to skip the iteration entirely:

Make an array of the row additions:

JavaScript

apply it via broadcasting:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement