Averaging a pivot table column

Question:

I have a pivot table which is counting the number of instances of pos by date. The code looks like:

pivot = Year1Data.reset_index()
           .pivot_table(index='date', 
                        values=['pos'],
                         aggfunc=[len])

I’m using len to count the number of pos that occur each day.

I get the output:

              len
              pos
date             
2016-02-12  573.0
2016-03-05   15.0
2016-03-06  620.0
2016-03-08  495.0
2016-03-10  622.0

I am then trying to average the pos column by using :

average_number_of_positions =  pivot["pos"].mean()

but I get a keyerror:

KeyError: 'pos'

I’ve tried different things to make it work, but to no avail.

Asked By: Stacey

||

Answers:

The column names of your pivot dataframe have two levels.

So something like this should work:

average_number_of_positions = pivot.loc[:,['len','pos']].mean()
Answered By: Tasko Olevski
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.