messy748
messy748

Reputation: 327

How can I add the values of one column based on a groupby in Python?

Suppose I have the following dataframe:

year count 2001 14 2004 16 2001 2 2005 21 2001 22 2004 14 2001 8

I want to group by the year column and add the count column for each given year. I would like my result to be

year count 2001 46 2004 30 2005 21

I am struggling a bit finding a way to do this, can anyone help?

Upvotes: 0

Views: 31

Answers (2)

GIRISH kuniyal
GIRISH kuniyal

Reputation: 770

Hope this may help !! Lets assume your pandas dataframe name is df. then groupby code run like below:

df.groupby('year')[['count']].sum()

It will return dataframe you want.

Upvotes: 1

artemis
artemis

Reputation: 7281

import pandas as pd

df = pd.read_csv("test.csv")
df['count'] = pd.to_numeric(df['count'])
#df['count'] = df.groupby(['year'])['count'].sum()

total = df.groupby(['year'])['count'].sum()

print(total)

Yields:

year
2001    46
2004    30
2005    21

Upvotes: 1

Related Questions