Suppose I have a NumPy 1d-array a
:
a = np.array([1, 2, 3])
and I have a function foo
:
def foo(x, p):
...
return y
I want to apply foo
on a
with, say, p
from 1 to 3 to make a 2d-array.
CodePudding user response:
Or just:
>>> a[:, None] ** np.arange(1, 4)
array([[ 1, 1, 1],
[ 2, 4, 8],
[ 3, 9, 27]], dtype=int32)
>>>
With a function:
def foo(x, p):
return x ** p
np.apply_along_axis(lambda x: foo(x, np.arange(1, 4)), 1, a[:, None])
array([[ 1, 1, 1],
[ 2, 4, 8],
[ 3, 9, 27]], dtype=int32)
CodePudding user response:
In you comment you say you want to give both arguments to function
For this purpose you can use map
and functools
like below:
from functools import partial
a = np.array([1, 2, 3])
def foo(x,y,z):
return list(z ** y x)
list(map(partial(foo, z=a), range(1,4), range(1,4)))
Output:
[
[3, 4, 5], # [1,2,3]**1 1
[3, 6, 11], # [1,2,3]**2 2
[3, 10, 29] # [1,2,3]**3 3
]
CodePudding user response:
Firstly, numpy
module support math function .So, if you want to apply mathematic function on an array you only have to write it as normal function or a lambda function, then apply it on your array .For example:
def foo(x,p):
return numpy.power(x,p)
Note : these much more matematical function in the numpy module . Try to take a look on them :) .