split dataframe values into a specified number of groups and apply function - pandas

Viewed 268
df=pd.DataFrame([1,4,1,3,2,8,3,6,3,7,3,1,2,9])

I'd like to split df into a specified number of groups and sum all elements in each group. For example, dividing df into 4 groups

1,4,1,3  2,8,3,6  3,7,3,1  2,9 

would result in

9
19
14
11

I could do df.groupby(np.arange(len(df))//4).sum(), but this won't work for larger dataframes

For example

df1=pd.DataFrame([1,4,1,3,2,8,3,6,3,7,3,1,2,9,1,5,3,4])
df1.groupby(np.arange(len(df1))//4).sum()

creates 5 groups instead of 4

3 Answers
Related