2

How can I export each dataframe with different name after using np.array_split?

I split my dataframe into multiple parts, let's say, 4 and I want to export them as separate dataframes with the corresponding name, for example, df_split_1.csv, df_split_2.csv, df_split_3.csv, df_split_4.csv and so on.

Clearly, I can do this with an approach of df_split[1].to_csv(r'W:\...\df_split_1.csv'), however, if I had 100 of these dataframes, doing this to each and one of them is not a long-term solution. So, the question is how can I split dataframe and export them as separate files?

My guess would be to create a loop that saves the files automatically, but I have not figured it out yet.

import numpy as np
import pandas as pd
    
df = pd.read_file(r'W:\...\dataframe.csv')
df_split = np.array_split(df, 4)

df_split[0].to_csv(r'W:\...\df_split_1.csv')
df_split[1].to_csv(r'W:\...\df_split_2.csv')
df_split[2].to_csv(r'W:\...\df_split_3.csv')
df_split[3].to_csv(r'W:\...\df_split_4.csv')

1 Answer 1

1

Loop with enumerate:

for i, v in enumerate(df_split, 1):
    v.to_csv(fr'W:\...\df_split_{i}.csv')
Sign up to request clarification or add additional context in comments.

2 Comments

What does 1 mean in enumerate(df_split, 1)?
@g12345kk It's the start value for iterator i, it starts from 1 index instead of 0. More on documentation: docs.python.org/3/library/functions.html#enumerate

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.