Home > Back-end >  Python-Name a series of dataframes with a for loop
Python-Name a series of dataframes with a for loop

Time:05-26

I know this a basic question but I am trying to call data from the database and define each of these dataframes as different variables.

This is what i have tried

lst=['A','B','C']
for i in range(len(lst)):
    globals()[lst[i]]=***SQL query to import dataframes***

This is what I am looking for:

print(A)
*** Some Dataframe ***

Any help would be appreciated

CodePudding user response:

IIUC you can cycle through a sql query with different variables like this:

lst=['A','B','C']
for i in lst:
     f"""
     SELECT * FROM TABLE WHERE COLUMN1 = '{i}'
     """

CodePudding user response:

I would recommend using the enumerate function doing for loop through list. This makes it possible for you to unpack the index, and the value of the current element. Like so:

lst=['A','B','C']
for index, value in enumerate(lst):
    # Do some code here
    pass

This is the pythonic way of looping through lists when accessing the values. Hope this helps.

  • Related