Save dataframes to multiple CSVs retaining dataframe name

Viewed 57

How can I export multiple dataframes to CSVs that have the same title, in general code?

I tried:

dframes_list = [economy, finance, language]

for i, df in enumerate(dframes_list, 1):
    filename_attempt1 = "{}.csv".format(i)
    filename_attempt2= f"{i}.csv"
    df.to_save(filename_attempt2)

Expected Output:

file saved: "economy.csv"
file saved: "finance.csv"
file saved: "language.csv"

2 Answers

I think in python is strongly not recommended create strings variables, because then generate strings is not trivial.

Then best is create another list for names in strings and use zip:

dframes_list = [economy, finance, language]
names = ['economy','finance','language']
for i, df in zip(names, dframes_list):
    filename_attempt1 = "df_{}.csv".format(i)

Another idea is create dict of DataFrames:

dframes_dict = {'economy': economy, 'finance': finance, 'language': language}
for i, df in dframes_dict.items():
    filename_attempt1 = "df_{}.csv".format(i)

If need working with dict of DataFrames use:

 for k, v in dframes_dict.items():

     v = v.set_index('date')
     #another code for processing each DataFrame

     dframes_dict[k] = v

If you're doing this on a notebook, you can use a hack where you search the locals() and you could use regex to match 'dframes_list = [.+]` that should return a string value

'dframes_list = [economy, finance, language]'

which then you can do replacing until you get to 'economy, finance, language' at which point you can split and get a list.

A colab version works like this,

temp_local = dict(locals())
data = {}
for k,v in temp_local.items():
  try:
    if re.match('dframes_list = \[.+\]', v):
      data[k] = v
      print(k, v)
  except:
    pass

then,

names = re.findall('\[.+\]', data[key])[0].replace('[', '').replace(']', '').split(',')

where key has been identified from the data dict.

This isn't recommended tho.

Related