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: How do I pass name of a dataframe to a function in a for loop?

for cnt in range (2,Maxcnt):
    X="DF"+ str(cnt)
    matchparts(DF1, X)
    print(X)

I want to send DF2 to DFn to matchparts function.. I tried sending it using matchparts(DF1, "DF"+ str(cnt)) the function recieves it as string rather than a DF

>Solution :

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

There are basically 3 ways in which you can do this :

  1. Using dictionary
  2. Using globals()
  3. Using eval(Not recommended)

Say you have dataframe in multiple variables, say DF1, DF2, DF3.

Using dictionary

To access them using the string name created on the run, you can store them in a dictionary at the first place.

eg

result = {
'DF1':DF1,
'DF2':DF2,
'DF3':DF3,
}

Now you can call your function as

for cnt in range (2,Maxcnt):
    X="DF"+ str(cnt)
    matchparts(DF1, result[X])
    print(result[X])

Using globals

You can do the same using globals() in python

globals()['DF1'] or globals()['DF2'] should give you the same.

So your function call would become

matchparts(DF1, globals()[X])
Example code
>>> import pandas as pd
>>> df1 = pd.DataFrame({'data':[1,2]})
>>> df1
   data
0     1
1     2
>>> globals()['df1']
   data
0     1
1     2

Using eval

Disclaimer : Not recommended due to security issue

Using eval your function call would become

matchparts(DF1, eval(X))
Example code
>>> import pandas as pd
>>> df1 = pd.DataFrame({'data':[1,2]})
>>> eval('df1')

   data
0     1
1     2
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