简体   繁体   中英

export csv in loop with the dataframe name as the filename

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 (eg, "weather") plus adding a fixed ending (eg, "_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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM