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
Georgy
  • 12,464
  • 7
  • 65
  • 73
asimo
  • 2,340
  • 11
  • 29
  • Possible duplicate of [Get the name of a Pandas DataFrame \[Python\]](https://stackoverflow.com/questions/31727333/get-the-name-of-a-pandas-dataframe-python) – Georgy May 21 '18 at 09:59
  • So you want to dynamically create variables from these functions? – zipa May 21 '18 at 10:00
  • @zipa : Yes, the parameter value should be dynamically appended to a variable in order to form a unique variable name/string – asimo May 21 '18 at 10:04
  • What's wrong with `df.name` attribute? What are you trying to achieve anyway? – Georgy May 21 '18 at 10:05

1 Answers1

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]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128