0

How can I write a function that takes in a variable and use the name of the variable to assign it as a string?

def one_function(dataframe):
 <does some numeric operation...>
 print('dataframe')

so for example

df_wow=pd.DataFrame([1,2,3])
one_function(df_wow)
'df_wow'
Different_data_frame=pd.DataFrame([99,98,100])
one_function(Different_data_frame)
'Different_data_frame'

EDIT

After doing some more research and with the comments and replies I came to the conclusion that it can't be done. I got around this by just passing another argument

def one_function(dataframe,name_arg):
 <does some numeric operation...>
 print(name_arg)

My end goal here was actually to name the index of the data frame. So actually I ended up writing the following function

def one_function(dataframe,name_arg):
 <does some numeric operation...>
 dataframe.index.name=name_arg
 return(dataframe)
2
  • 2
    The question is, what for? Commented Jul 28, 2017 at 20:13
  • 2
    Quite simply, you can't Commented Jul 28, 2017 at 20:18

1 Answer 1

1

No you cant, when passing a parameter only the value of the parameter is passed (copied) to the function.

However, you can achieve something similar if you use keyword arguments:

In [1]: def one_function(**kwargs):
 ...: print(kwargs.keys()[0])
 ...: 
In [2]: one_function(foo=5)
foo

This example prints one (random) argument, if you have more than one you can loop through the .keys() list and print them all or do whatever you want with them.

answered Jul 28, 2017 at 20:19
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.