dingaro
dingaro

Reputation: 2342

Crosstabin Pandas?

I have DataFrame in Pandas like this:

 df = pd.DataFrame({"price_range": [0,1,2,3,0,2], "blue":[0,0,1,0,1,1], "four_g":[0,0,0,1,0,1]})

I have line like this: pd.crosstab(df['price_range'], df["blue"])

Nevertheless, now I only see only for example how many "blue" 0 and 1 is for each "price_range", but I want to exapnd this code and also know how many "four_g" 0 and 1 is for each "price_range". How can do that? Please help me

Upvotes: 0

Views: 64

Answers (2)

Andy L.
Andy L.

Reputation: 25239

a simplest way is using 2 crosstab through list comprehension with concat

cols = ['blue', 'four_g']
df_out = pd.concat([pd.crosstab(df['price_range'], df[col]) 
                            for col in cols], keys=cols, axis=1)

Out[1116]:
            blue    four_g
blue           0  1      0  1
price_range
0              1  1      2  0
1              1  0      1  0
2              0  2      1  1
3              1  0      0  1

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153460

One way is to use 'melt':

df_out = df.melt('price_range')

pd.crosstab(df_out['price_range'], df_out['variable'], df_out['value'], aggfunc='sum')

Output:

variable     blue  four_g
price_range              
0               1       0
1               0       0
2               2       1
3               0       1

Another way is to use groupby:

df.groupby('price_range')[['blue','four_g']].sum()

Output:

             blue  four_g
price_range              
0               1       0
1               0       0
2               2       1
3               0       1

Upvotes: 3

Related Questions