Home > Mobile >  Python Functions: Pass parameter as string and reference?
Python Functions: Pass parameter as string and reference?

Time:02-04

I have a knot in my head. I wasn't even sure what to google for. (Or how to formulate my title)

I want to do the following: I want to write a function that takes a term that occurs in the name of a .csv, but at the same time I want a df to be named after it.

Like so:

def read_data_into_df(name):
     df_{name} = pd.read_csv(f"file_{name}.csv")

Of course the df_{name} part is not working. But I hope you get the idea.

Is this possible without hard coding?

Thanks!

CodePudding user response:

IIUC, you can use globals :

def read_data_into_df(name):
     globals()[f"df_{name}"] = pd.read_csv(f"file_{name}.csv")
     

CodePudding user response:

If I were you I would create a dictionary and create keys with

dictionary = f"df_{name}: {whatever_you_want}"

CodePudding user response:

If there are only a couple of dataframes, just accept the minimal code repetition:

def read_data_into_df(name):
     return pd.read_csv(f"file_{name}.csv")

...

df_ham = read_data_into_df('ham')
df_spam = read_data_into_df('spam')
df_bacon = read_data_into_df('bacon')

...

# Use df_ham, df_spam and df_bacon

If there's a lot of them, or the exact data frames are generated, I would use a dictionary to keep track of the dataframes:

dataframes = {}

def read_data_into_df(name):
     return pd.read_csv(f"file_{name}.csv")

...

for name in ['ham', 'spam', 'bacon']:
    dataframes[name] = read_data_into_df('name')
...

# Use dataframes['ham'], dataframes['spam'] and dataframes['bacon']
# Or iterate over dataframes.values() or dataframes.items()!
  • Related