0

I have a custom Python function that uses the input of a model to create a data frame of the predicted y-values, probabilities, and some other features. I am trying to extract the physical variable name and use it as column within the data frame. In the function the "model" variable signifies a defined model. Is it possible extract the physical string and use it to create a new column?

Below is an extremely basic reproducible example of my code

from sklearn.linear_model import LogisticRegression 
import pandas as pd```

df = {'odds_h': [150, 200, -300]}

log_reg = LogisticRegression()

def model_summary(model):
    
    df_summary = pd.DataFrame({'odds_h': df['odds_h'],
                               'model_type': model})
    
    return(df_summary)

model_summary(log_reg)

Here is what the data frame output currently displays

current output

Here is the intended output

desired output

mf17
  • 91
  • 6
  • 1
    What *exactly* is the expected "*physical variable name*"/"*physical string*"? You want to get `"model"`? Please provide sample input and output. – Gino Mempin May 11 '21 at 03:33
  • In the variable within function, I will use defined models such as "log_reg", "gbc", "rf", etc. I would like to call the input directly as text in a column within the data frame. I added in examples above – mf17 May 11 '21 at 04:13
  • See [How to get the original variable name of variable passed to a function](https://stackoverflow.com/questions/2749796/how-to-get-the-original-variable-name-of-variable-passed-to-a-function) – Gino Mempin May 11 '21 at 04:50

1 Answers1

0

If you want to get the variable name of the variable passed to the function,here are two simple way.

  • get_var_name may give mutiple result if you have a lot variable are same value.
  • easy_way maybe a little hard to use,need pass the name of variable.
  • dict_way need pass a dict to the function.

Also you can see these link to get more solutions.

python obtain variable name of argument in a function

How to get the original variable name of variable passed to a function

code:

def get_var_name(arg):
    return [k for k,v in globals().items() if v == arg]

def easy_way(arg,name):
    #dosomething with arg
    return name

def dict_way(**kwargs):
    for arg_name in kwargs:
        return arg_name

a = 1
b = 1
c = 2
print(get_var_name(a))
print(easy_way(a,"a"))
print(dict_way(a = 1))

result:

['a', 'b']
a
a
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21