1

I have five DataFrames, df1, df2, df3, df4, df5.

I can save each one individually with:

df1.to_csv('~/Desktop/df1.tsv', index=False, header=False, sep='\t')
df2.to_csv('~/Desktop/df2.tsv', index=False, header=False, sep='\t')
...

Can I do this in a loop where the file path ends with the name of the variable that holds the Dataframe?

1 Answer 1

4

when you say

the name of the DataFrame

do you mean the name of the variable that holds the dataframe? that won't work.

but here's something that will work:

dfs = [df1, df2, df3, df4, df5]
for i, df in enumerate(dfs):
   df.to_csv(f'~/Desktop/df{i}.tsv', index=False, header=False, sep='\t')

if you wanted unique names

dfs = [df1, df2, df3, df4, df5]
names = ["apple", "bananna", "cherry", "drizz", "ebola"]
for name, df in zip(names, dfs):
   df.to_csv(f'~/Desktop/df{name}.tsv', index=False, header=False, sep='\t')
Sign up to request clarification or add additional context in comments.

2 Comments

Rereading your answer, if I wanted to save the DataFrames with unique names, e.g. apple, orange, peach, pear - is this possible? So instead of df1,df2,dfN, what if the variable names were apple, orange, peach, etc.
@TipsyHyena easy. check the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.