D. Brito
D. Brito

Reputation: 206

Grouping by entries in a column in Pandas Dataframe

I have a Pandas DataFrame with id as index, brand, type and price as columns that looks like the following:

                   brand  type  price
id                                                                 
1234567            A      X         39.0
2391923            A      Y         20.0
1595354            B      X         12.4
6699874            B      Z         88.2
0998877            B      Z         100.1
8791392            C      X         32.0

I would like to "group" by brand and category to find the average prices organized like such:

             X      Y      Z
brand_A  $$.$$  $$.$$  $$.$$
brand_B  $$.$$  $$.$$  $$.$$
brand_C  $$.$$  $$.$$  $$.$$

I know that using group_by with the .mean() method gets me close to what I want but not exactly. Any tips are appreciated.

Upvotes: 2

Views: 142

Answers (1)

Umar.H
Umar.H

Reputation: 23099

i think you can use .groupby and .unstack

df1 = df.groupby(['brand','type'])['price'].mean().unstack(1,fill_value=0)

print(df1)

type      X     Y      Z
brand
A      39.0  20.0   0.00
B      12.4   0.0  94.15
C      32.0   0.0   0.00

Upvotes: 3

Related Questions