Warm tip: This article is reproduced from stackoverflow.com, please click
dataframe pandas pandas-groupby python python-3.x

Split one excel file into multiple with specific number of rows in Pandas

发布于 2020-03-27 15:39:35

Let's say I have an excel file with 101 rows, I need to split and write into 11 excel files with equivalent row number 10 for each new file, except the last one since there is only one row left.

This is code I have tried, but I get KeyError: 11:

df = pd.DataFrame(data=np.random.rand(101, 3), columns=list('ABC'))
groups = df.groupby(int(len(df.index)/10) + 1)
for i, g in groups:
    g.to_excel("%s.xlsx" % i, index = False, index_lable = False)

Someone could help with this issue? Thanks a lot.

Reference related: Split pandas dataframe into multiple dataframes with equal numbers of rows

Questioner
ahbon
Viewed
18
jezrael 2020-01-31 16:14

I think you need np.arange:

df = pd.DataFrame(data=np.random.rand(101, 3), columns=list('ABC'))
groups = df.groupby(np.arange(len(df.index))//10)
for i, g in groups:
    print (g)