问题
I want to apply function to every column in matrix. I would like to use function with arguments but I don't know how to do it, things I tried ends with an error.
code I am runnung
import numpy as np
M = np.array([[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]])
def my_function(arr, arg="default"):
print arg
return arr
def my_function_allong_axis(M, argument):
return np.apply_along_axis(my_function, axis=0, arr=M, arg=argument)
my_function_allong_axis(M, "something else")
this will produce TypeError: apply_along_axis() got an unexpected keyword argument 'arg'
回答1:
Solution:
def my_function_allong_axis(M, argument):
return np.apply_along_axis(my_function, 0, M, argument)
keyword arguments were the problem, because of the old numpy
回答2:
You're not passing the "arg" argument to "my_function" in the "apply_along_axis", so it will always print the default value. I adjusted your code as so, and it works as you wanted:
def my_function_allong_axis(M, argument):
return np.apply_along_axis(my_function, axis=0, arr=M, arg=argument)
来源:https://stackoverflow.com/questions/28452716/python-how-to-put-argument-to-function-with-numpy-aply-along-axis