I have a list of dataframes that I am writing as individual csv’s using a for loop, I wish to name each csv based on a list of names I have, currently stored as a list of string.
Dataframes are saved as df_list, this is the code I am using to write the csv files which currently just names them sequentially.
string_list = ['one', 'two', 'three']
for i, df in enumerate(df_list, 1):
df.to_csv(f'file_{i}.csv')
2
You would need to index your list:
string_list = ['one', 'two', 'three']
for i, df in enumerate(df_list):
df.to_csv(f'file_{string_list[i]}.csv')
But better use zip
, which is the pythonic way to iterate over several lists in parallel:
for s, df in zip(string_list, df_list):
df.to_csv(f'{s}.csv')
It seems that your code is already quite close to what you want. The following would create the files first_name.csv
, name_two.csv
, and third_thing_here.csv
out of df_list
, assuming df_list
is a list of three pandas dataframes.
name_list = ["first_name", "name_two", "third_thing_here"]
for i, df in enumerate(df_list):
df.to_csv(f"{name_list[i]}.csv")