Stacey
Stacey

Reputation: 5107

Averaging a pivot table column

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.

Upvotes: 0

Views: 66

Answers (1)

Tasko Olevski
Tasko Olevski

Reputation: 476

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()

Upvotes: 1

Related Questions