1

I have tried searching the forums, but couldn't really find one for the problem I am facing.
I am trying to create a dataframe within a function. However the name of the dataframe is something I want to dynamically create based on a parameter value that is passed to the function.

Am not sure how I can do this in a quick way. Can you please advise.

Eg:

def Upload(file, ABC):
    df_ABC = pd.read.......
    return df_ABC


def Upload(file, NYK):
    df_NYK = pd.read.......
    return df_NYK
4
  • Possible duplicate of Get the name of a Pandas DataFrame [Python] Commented May 21, 2018 at 9:59
  • So you want to dynamically create variables from these functions? Commented May 21, 2018 at 10:00
  • @zipa : Yes, the parameter value should be dynamically appended to a variable in order to form a unique variable name/string Commented May 21, 2018 at 10:04
  • What's wrong with df.name attribute? What are you trying to achieve anyway? Commented May 21, 2018 at 10:05

1 Answer 1

1

I want to dynamically create based on a parameter value that is passed to the function.

You can use locals.

locals()['df_'+ ABC] = pd.read....

But it's not recommended to do this. Use a dictionary instead.

my_dict = {}
my_dict['df_' + ABC] = pd.read.......

When you want to return value the dataframe just use bracket notation.

return my_dict['df_' + ABC]
Sign up to request clarification or add additional context in comments.

3 Comments

@ Mihai Alexandru-lonut : Can you please share a template how the dictionary can be used for this..
And how would the return statement look like. return df_ ?
@asimo, return my_dict['df_' + ABC]

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.