简体   繁体   中英

How to add multiple columns as a result of groupby pandas python

Let's say I have a dataframe:

date | brand | color
--------------------
2017 | BMW   | red
2017 | GM    | blue
2017 | BMW   | blue
2017 | BMW   | red
2018 | BMW   | green
2018 | GM    | blue
2018 | GM    | blue
2018 | GM    | red

As a result I want to have something like:

date | brand | red | blue | green
---------------------------------
2017 | BMW   |  2  |  1   |   0
     |  GM   |  0  |  1   |   0
2018 | BMW   |  0  |  0   |   1
     |  GM   |  1  |  2   |   0

I found that I need to use groupby + size, something like:

df[df['color'] == 'red'].groupby([df['date'], df['brand']]).size()

But this gives me Series only for single color, while I want to have complete dataframe as shown higher.

As simple as you saw..

Option 1 crosstab

pd.crosstab([df['date'],df['brand']], df['color'])
Out[30]: 
 color          blue   green   red
date   brand                      
2017   BMW         1       0     2
       GM          1       0     0
2018   BMW         0       1     0
       GM          2       0     1

Option 2 : groupby and unstack

df.groupby(['date ',' brand ',' color'])[' color'].count().unstack(-1).fillna(0)
Out[40]: 
 color          blue   green   red
date   brand                      
2017   BMW       1.0     0.0   2.0
       GM        1.0     0.0   0.0
2018   BMW       0.0     1.0   0.0
       GM        2.0     0.0   1.0

Option 3 pivot_table

pd.pivot_table(df.reset_index(),index=['date','brand'],columns='color',values='index',aggfunc='count').fillna(0)
Out[57]: 
color          blue   green   red
date brand                       
2017  BMW       1.0     0.0   2.0
      GM        1.0     0.0   0.0
2018  BMW       0.0     1.0   0.0
      GM        2.0     0.0   1.0
df.groupby(['date','brand'])['red','blue','green'].count()

要么...

df.groupby(['date','brand']).agg('count')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM