3

I have the following code

import pandas as pd
df = pd.DataFrame(columns=['var1', 'var2','var3'])
df.loc[0] = [0,1,2]

def RS():
    x = 123
    y = 456
    z = 'And some more random shit'
    return x+y

def BS():
    x = -890
    y = (456*1)+90
    z = 'And some more random shit'
    return x-y

def MyCompute(srt, srt_string):
    df[srt_string] = srt()
    df['1min' + srt_string] = 1-df[srt_string]

MyCompute(srt=RS, srt_string='RS')
MyCompute(srt=BS, srt_string='BS')

Is there a way to avoid the double RS and double BS in calling the MyCompute function?

0

4 Answers 4

7

Use the attribute __name__ :

def MyCompute(srt):
    df[srt.__name__] = srt()
    df['1min' + srt.__name__] = 1 - df[srt.__name__]

MyCompute(srt=RS)
MyCompute(srt=BS)
Sign up to request clarification or add additional context in comments.

Comments

1

Put your functions in a dictionary, then you can look up the function by name.

compute_dict = {"RS": RS, "BS": BS}
def MyCompute(srt_string):
    srt = compute_dict[srt_string]
    df[srt_string] = srt()
    df['1min' + srt_string] = 1-df[srt_string]

Comments

0

Yes, you can use the __name__ attribute of a function, e.g. RS.__name__ instead of 'RS'

Comments

0

Yes, you can just get the name of the function:

def MyCompute(srt):
    df[srt.__name__] = srt()
    df['1min' + srt.__name__] = 1-df[srt.__name__]

MyCompute(srt=RS)
MyCompute(srt=BS)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.