batmanforever
batmanforever

Reputation: 155

Pivot table sum years

I created

cvv=dd.pivot_table('quantity',index='date',aggfunc=sum)

date   quantity
2012  555
2013  397 
2014  876 
2015  129 
2016  984 
2017    5

I'd like to take and sum(quantity) only the last 2 years from the data frame.

Is it easy way to write this?

Upvotes: 1

Views: 46

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

We can first perform a filtering, then select the column, and call sum on it, like:

cvv[cvv['date'] >= 2015]['quantity'].sum()
#   \_________ ________/\_____ ____/ \_ _/
#             v               v        v
#           filter     select column   aggregate

Given the date column is the index, we can also use .loc[2015:2017] to obtain the list rows, and then perform the aggregate over it:

cvv.loc[2015:2017]['quantity'].sum()
#   \____ _______/\_____ ____/ \_ _/
#        v              v        v
#      filter   select column   aggregate

Upvotes: 1

Related Questions