Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Export dataframes as separate files after using `np.array_split` in Python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')

>Solution :

Loop with enumerate:

for i, v in enumerate(df_split, 1):
    v.to_csv(fr'W:\...\df_split_{i}.csv')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading