Skip to content Skip to sidebar Skip to footer

Split A Pandas Dataframe Every 5 Rows

I have a dataframe df : df ==================================== | COLUMN_Y | ==================================== | value1 | |

Solution 1:

Use floor division on the index to create your groups, then we can use DataFrame.groupby to create different dataframes:

grps = df.groupby(df.index // 5)

for _, dfg in grps:
    print(dfg)

  COLUMN_Y
0   value1
1   value2
2   value3
3   value4
4   value5 

  COLUMN_Y
5   value6
6   value7
7   value8
8   value9
9  value10 

   COLUMN_Y
10  value11
11  value12
12  value13
13  value14
14  value15 

   COLUMN_Y
15  value16 

Solution 2:

The code below will do the split and then save to different CSVs:

split_size = 5
dfs = [df.loc[i:i+split_size-1,:] for i in range(0, len(df),split_size)]
for _, frame in enumerate(dfs):
    frame.to_csv('df'+str(_)+'.csv', index=False)

Solution 3:

Try a list comprehension:

listofdataframes = [df.iloc[i:i + 5] for i in range(0, len(lst), 5)]

Post a Comment for "Split A Pandas Dataframe Every 5 Rows"