0

I have a list of dataframe objects:

mydfs= [df1,df2,df3]

And a list of names I'd like to assign to them:

mynames = ['customers','transactions','dates']

I can't figure out how to get them out of the list. I just want to index these dataframes directly like customers['name'].

I've tried just assigning them directly using zip:

for name,df in zip(mynames, mydfs):
    name = df

But when I check customers.head() etc. it is not defined.

How can I get them out of this list? I want them out of the list and as regular dataframes that I can start indexing as normal.

Solution: when reading them in use globals() to assign a name to the DF. Skip adding them to the list entirely.

for filename in all_files:
    name = ntpath.basename(filename)
    name = name.replace('.dat','')
    try:
        globals()[name] = pd.read_csv(filename, sep='\t', engine='python')
    except:
        print(f'File not read:{filename}')
SCool
  • 3,104
  • 4
  • 21
  • 49
  • `d={k:v for v in mydfs for k in mynames}` – anky Jul 12 '19 at 12:10
  • But that's just creating a dictionary. I want them out of the list altogether. So I can start indexing them as regular dataframes. `customers['name']` etc. I want to end up with three dataframes called `customers`, `transactions` and `dates`. I don't know the technical term but I'd like them 'free roaming' and not stuck in a list or dictionary. – SCool Jul 12 '19 at 12:13
  • check the solutions from the dupe link. I store them in dicts when a name is required `print(d['customers'])` prints the first dataframe – anky Jul 12 '19 at 12:15
  • they're still "regular" data frames, they're just kept within a dict object which gives you the ability to index by key/value pair. `d['customers']['name']` will give you the same as `df1['name']`. – David Zemens Jul 12 '19 at 12:20
  • BTW in your zip attempt, `name = df` is overwriting the name "customers" with the dataframe. If you did instead: `print(name, df.head)` that would work. – David Zemens Jul 12 '19 at 12:21

0 Answers0