Reputation: 337
Im trying to save each element from a list to each separate csv files. each element is a dataframe.
I used the following codes, however, the problem is that the files that it saves are only from the first or last element of the list from the two following codes respectively. e.g. the output files are all identical
for x in allcity:
for a in range(0,20):
x.to_csv('msd{}.csv'.format(a))
for a in range(0,20):
for x in allcity:
x.to_csv('msd{}.csv'.format(a))
Upvotes: 1
Views: 519
Reputation: 724
Try f-strings This is the easiest answer here
counter = 0
for x in allcity:
x.to_csv(f'msd{counter}.csv')
counter += 1
Upvotes: 0
Reputation: 3309
The problem is that the nested loop will write the last data frame from the allcity
list to the range of values in both cases. You have two options:
counter = 0
for x in allcity:
x.to_csv('msd{}.csv'.format(counter)
counter += 1
or
for (counter, x) in enumerate(allcity):
x.to_csv('msd{}.csv'.format(counter)
Upvotes: 1
Reputation: 18647
IIUC, i think you need:
for a, x in enumerate(allcity):
x.to_csv('msd{}.csv'.format(a))
Upvotes: 2