4

I am trying to output multiple csvs from a function - but also name the csv per the name of the df.

dfs = ( df1, df2 , df3 , df4)

for df in dfs:

    def to_csvs(df, 'df name as csv name'):
        df.to_csv('example.csv')
        return df

I want to use a loop to feed in my multiple dfs and have a parameter in the function input that would name the csv output as well - is that possible?

cs95
  • 379,657
  • 97
  • 704
  • 746
Chris90
  • 1,868
  • 5
  • 20
  • 42
  • What have you tried? Also, I recommend not defining a function inside a for-loop. Do it outside and then call the function inside the loop. – Ian Thompson Feb 20 '19 at 22:33

1 Answers1

2

If you want to customize the CSV names you could store your DFs in a dict with the key as the CSV name, e.g.:

dfs = {"df1 name":df1, "df2 name":df2}  # ..etc

for k, v in dfs.items():
    v.to_csv('./{}.csv'.format(k)))
Toby Petty
  • 4,431
  • 1
  • 17
  • 29