Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Functions: Pass parameter as string and reference?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

IIUC, you can use globals :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading