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
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)
It generates an error:
ValueError: Grouper and axis must be same length
@ahbon - Maybe typo from me in
)
, can you checkdf.groupby(np.arange(len(df.index))//10)
Wondeful, problem solved. Thank you.