0

I have a question about how to apply a function to vectors in a 3D numpy array. My problem is the following: let's say I have an array like this one:

a = np.arange(24)
a = a.reshape([4,3,2])

I want to apply a function to all following vectors to modify them:

[0 6], [1 7], [2 8], [4 10], [3 9] ...

What is the best method to use? As my array is quite big, looping in two of the three dimension is quite long...

Thanks in advance!

0

1 Answer 1

1

You can use function np.apply_along_axis. From the doc:

Apply a function to 1-D slices along the given axis.

For example:

>>> import numpy as np
>>> a = np.arange(24)
>>> a = a.reshape([4,3,2])
>>> 
>>> def my_func(a):
...   print "vector: " + str(a)
...   return sum(a) / len(a)
... 
>>> np.apply_along_axis(my_func, 0, a)
vector: [ 0  6 12 18]
vector: [ 1  7 13 19]
vector: [ 2  8 14 20]
vector: [ 3  9 15 21]
vector: [ 4 10 16 22]
vector: [ 5 11 17 23]
array([[ 9, 10],
       [11, 12],
       [13, 14]])

In example above I've used 0th axis. If you need n axes you can execute this function n times.

Sign up to request clarification or add additional context in comments.

1 Comment

These don't seem to be the vectors that the OP is looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.