Home > Software design >  export csv in loop with the dataframe name as the filename
export csv in loop with the dataframe name as the filename

Time:11-16

I have a list of dataframes that I wish to operate on my functions and export the output individually to my directory with the dataframe name as the filenames (e.g., "weather") plus adding a fixed ending (e.g., "_perYear"). How can I do that? I structured my code like this:

df_list = [weather, air, ground]
for df in df_list:
    df_perYear = myFunction1(data = df) # my own function
    df_perYear.to_csv("..\weather_perYear.csv") # how to loop the filename?

Expected output: export three csv files with the filenames in weather_perYear.csv, air_perYear.csv, ground_perYear.csv.

Thanks!

CodePudding user response:

If I understand your question correctly, you want something like this:

for df in df_list:
    name = [x for x in globals() if globals()[x] is df][0]
    print(f"..\\{name}_perYear.csv")

It's not great though, if this is pandas, you might consider using something like df.name to set the name of the dataFrame if it doesn't already exist.

See also Get the name of a pandas DataFrame

  • Related