Klausos Klausos
Klausos Klausos

Reputation: 16040

How to sum values of one column and group them by another column

I have a data frame like this:

df
time   type qty
12:00  A    5
13:00  A    1
14:00  B    9

I need to sum the values of qty and group them by type. This is how I do it, but it seems to be not working, because I don't know how to add qty.

keys = df['type'].unique()
summary = pd.DataFrame()
for k in keys:
    summary[k] = df[df['type']==k].sum()

Upvotes: 2

Views: 2526

Answers (2)

E_SD
E_SD

Reputation: 1

To make sure you are summing up the column you want to:

df.groupby(by=['type'])['qty'].sum()

Upvotes: 0

Andy Hayden
Andy Hayden

Reputation: 375377

GroupBy has a sum method:

In [11]: df.groupby("type").sum()
Out[11]:
      qty
type
A       6
B       9

see the groupby docs.

Upvotes: 1

Related Questions