user8270077
user8270077

Reputation: 5071

pivot_table returns KeyError in Pandas

I am getting a key error when I use pivot_table in pandas I cannot explain:

My data:

df1
make    body-style  engine-size
0   alfa-romero convertible 130
1   alfa-romero convertible 130
2   alfa-romero hatchback   152
3   audi    sedan   109
4   audi    sedan   136
5   audi    sedan   136
6   audi    sedan   136
7   audi    wagon   136
8   audi    sedan   131
10  bmw sedan   108

The code:

pd.pivot_table(df1, columns = ['make', 'body-style'], \
               margins = True, aggfunc = {'engine-size' : 'mean', 'make' : 'count'})
KeyError: 'make'

Upvotes: 0

Views: 411

Answers (1)

BENY
BENY

Reputation: 323316

You can use agg

df.groupby(['make', 'body-style']).agg({'engine-size' : 'mean', 'make' : 'count'})
Out[128]: 
                         make  engine-size
make        body-style                    
alfa-romero convertible     2        130.0
            hatchback       1        152.0
audi        sedan           5        129.6
            wagon           1        136.0
bmw         sedan           1        108.0

Upvotes: 1

Related Questions