python how to put argument to function with numpy aply_along_axis

百般思念 提交于 2021-02-07 14:20:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!