Aggregate rows in pandas dividing rows in n groups

Viewed 47

Consider the example dataframe.

df = pd.DataFrame([[1,'u'],[2,'u'],[3,'u'],[4,'u']],columns=['useful','useless'])

I want to have a new dataframe with the aggregate value of every n datapoints for column 'useful'. For the example, let's say n = 2. This would be the desired output.

new_df = pd.DataFrame([[3],[7]],columns=['useful'])

I have achieved this, but I believe there should be an easier way around it. My approach was as follows:

new_df = df[['useful']].to_numpy()
new_df = new_df.reshape(2, 2)

p = []

for i in new_df:
    p.append(i.sum())

new_df = pd.DataFrame(p, columns=['useful'])

if I needed, for example, groups of 3, I would just add 2 more 0 datapoints in order for the reshape function to work. For Which output would be as follows:

new_df = pd.DataFrame([[6],[4]],columns=['useful'])
0 Answers
Related