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')
CodePudding user response:
Loop with enumerate
:
for i, v in enumerate(df_split, 1):
v.to_csv(fr'W:\...\df_split_{i}.csv')