Amani
Amani

Reputation: 18123

Pandas pivot table with mean

I have a pandas data frame, df, that looks like this;

index  New  Old  MAP      Limit  count
1       93   35   54       > 18      1
2      163   93  116       > 18      1
3      134   78   96       > 18      1
4      117   81   93       > 18      1
5      194  108  136       > 18      1
6      125   57   79      <= 18      1
7       66   39   48       > 18      1
8      120   83   95       > 18      1
9      150   98  115       > 18      1
10     149   99  115       > 18      1
11     148   85  106       > 18      1
12      92   55   67      <= 18      1
13      64   24   37       > 18      1
14      84   53   63       > 18      1
15      99   70   79       > 18      1

I need to create a pivot table that looks like this

Limit   <=18   >18
New      xx1   xx2
Old      xx3   xx4
MAP      xx5   xx6

where values xx1, xx2, xx3, xx4, xx5, and xx6 are the mean of New, Old and Map for respective Limit. How can I achieve this? I tried the following without success.

table = df.pivot_table('count', index=['New', 'Old', 'MAP'], columns=['Limit'], aggfunc='mean')

Upvotes: 4

Views: 9980

Answers (1)

piRSquared
piRSquared

Reputation: 294328

Solution

df.groupby('Limit')['New', 'Old', 'MAP'].mean().T

Limit  <= 18        > 18
New    108.5  121.615385
Old     56.0   72.769231
MAP     73.0   88.692308

Upvotes: 5

Related Questions