Home > Enterprise >  Python: How do I pass name of a dataframe to a function in a for loop?
Python: How do I pass name of a dataframe to a function in a for loop?

Time:08-07

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

CodePudding user response:

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
  • Related