0

I have a function, which calculate features from my data. Here is a dummy sample of it

import numpy as np
val1=[1,2,3,4,5,6,7,8,9]
val2=[2,4,6,8,10,12,14,16]
data=[]
def feature_cal(val):
    val=np.array(val)
    value=val*2
    data.append(np.mean(value))
feature_cal(val1)
feature_cal(val2)

What i want is to define the function np.mean() out of my function feature_cal.
Pseudo code

def feature_cal(val,method):
    val=np.array(val)
    value=val*2
    data.append(method(value))
feature_cal(val1,method=np.mean())
feature_cal(val2,method=np.mean())

This will help me to calculate other features such as np.std(), np.var() without changing the original function

1
  • 1
    Remove paranthesis: feature_cal(val1,method=np.mean). Commented Apr 28, 2019 at 7:47

3 Answers 3

4

To pass the function you need to remove the parentheses after np.mean:

import numpy as np

def feature_cal(val, method):
    val = np.array(val)
    value = val*2
    data.append(method(value))

feature_cal(val1, method=np.mean)
feature_cal(val2, method=np.mean)

EDIT

If you need to pass arguments to np.mean you can use functools.partial:

import numpy as np
import functools

def feature_cal(val, method):
    val = np.array(val)
    value = val*2
    data.append(method(value))

bound_function = functools.partial(np.mean, axis=1)
feature_cal(val1, method=bound_function)
feature_cal(val2, method=bound_function)
Sign up to request clarification or add additional context in comments.

1 Comment

if i have to pass some parameters to np.mean() such as axis=0 or axis=1. How can i pass it this way when i am not using parentheses.
0

If I got you correctly you need to pass callable and not result of function invocation as you do now. So this line

feature_cal(val1,method=np.mean())

Shouls read

feature_cal(val1,method=np.mean)

Comments

0

You can simply insert a method as a parameter into a function by entering the name of the method (without parentheses) and by reading the function you will call(with parentheses) the inserted parameter

    def feature_cal(val,method):
        val=np.array(val)
        value=val*2
        data.append(method(value))



   feature_cal(val1,method=np.mean)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.