Search code examples
pythonpython-3.xloopslist-comprehensionexport-to-csv

Create/ Export DataFrames to csv in a list comprehension


I have 4 DFs

jeep_1 = jeep_data[jeep_data['Distance (km)'] < 5]
jeep_2 = jeep_data[(jeep_data['Distance (km)'] >= 5) & (jeep_data['Distance (km)'] <= 10)]
jeep_3 = jeep_data[(jeep_data['Distance (km)'] >= 11) & (jeep_data['Distance (km)'] <= 20)]
jeep_4 = jeep_data[jeep_data['Distance (km)'] > 21]

I then have this code:

list_df = [jeep_1, jeep_2, jeep_3, jeep_4]

[item.to_csv('/Users/jacob/Desktop/Jeepney PROJECT 2/jeep_{}.csv'.format(???)) for item in list_df]

The list is a list of dataframes.

I want to save them with different file names jeep_1.csv, jeep_2.csv, etc.

How do I access the last element of the dataframe name jeep_2, or how can achieve this?

Thank you !


Solution

  • Try maybe? Although might not be the best solution...

    str(my_list.index(item))
    

    Although this answers your question, I would probably name the files after the variables:

    for item in my_list:
        item.to_csv('/Users/jacob/Desktop/Jeepney PROJECT 2/' + item + '.csv')
    

    if you want to be more accurate you can import os, and use os.path.join(your_dir, file_name, ".csv")