2

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"

asd
  • 1,245
  • 5
  • 14

2 Answers2

3

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks. How do I update the dataframes or at least the dictionary key? If I do ```df = df.set_index('date')``` in the forloop, nothing changes when I run outside the forloop: ```dframes_list['economy']``` – asd Feb 16 '21 at 08:19
  • @asd - Give me a sec. – jezrael Feb 16 '21 at 08:19
  • 1
    @asd - added to answer, you need set fictionary of dfs in last step. – jezrael Feb 16 '21 at 08:22
0

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.

gezibash
  • 36
  • 1
  • 2