0

I have multiple dataframes (e.g. df0, df1, df2, df3) that I need to iterate through, but the number of dataframes is arbitrary and is variable to change when I run this script on different datasets. I need to produce a list of these dataframes (using a loop):

dfs = [df0,df1,df2,df3]

So far this is what I have...

dfs = []
for i in range(4):
    dfs.append('df'+str(i))

However, this returns:

dfs = ['df0', 'df1', 'df2', 'df3']

Is there a way to convert this list of strings into a list of dataframes? Or another way to write the loop, perhaps?

The goal is to create an excel document that is printable. I need to take a dataframe with 24 columns and any number of rows (from 5 entries to over 100). Because it needs to be printable, I have to split the dataframe into multiple dataframes, each with column labels and 3 rows per page, with one dataframe on each page. Since the number of dataframes I need to produce is dependent on the number of rows in the original dataframe, it involved producing the dataframes uniquely in a loop. Here's the code I used to produce the dataframes:

 og = pd.ExcelFile(file).parse('Sheet1')

 sheets = int(len(og)/3)
 if (len(og)%3) != 0:
     sheets = sheets + 1

frames = [og.loc[i*3:(3*i + 2)] for i in range(sheets)]

for i in range(len(frames)):
     exec('df' +str(i)+ '= frames[i].transpose()')
  • Please help me understand why your dataframes are not inside a list to begin with. – cs95 Jan 10 '18 at 20:51
  • 1
    Also, there is an answer to your question, but it would be giving you what you want, not what you need (the two are different). It would be good to start with how these dataframes are created. – cs95 Jan 10 '18 at 20:55
  • 1st There is way to create the list of df .2nd Base on my knowledge I can not find a way to convert the list of string to list of df (even have, it will be overkilled) – BENY Jan 10 '18 at 20:57
  • @Wen Actually, really the only (filthy) way of doing it is by querying `globals`. But it should be avoided in favour of better programming practices. – cs95 Jan 10 '18 at 20:59
  • @cᴏʟᴅsᴘᴇᴇᴅ yeah, global, variable will do it – BENY Jan 10 '18 at 20:59
  • For starters, when generating the dataframes, you should put them inside a list, or a dictionary. – cs95 Jan 10 '18 at 21:04

0 Answers0