假设我有一个数据框:
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
因此我希望有类似的东西:
date | brand | red | blue | green
---------------------------------
2017 | BMW | 2 | 1 | 0
| GM | 0 | 1 | 0
2018 | BMW | 0 | 0 | 1
| GM | 1 | 2 | 0
我发现我需要使用groupby + size,例如:
df[df['color'] == 'red'].groupby([df['date'], df['brand']]).size()
但是这给了我系列仅用于单色,而我希望有更高的完整数据帧。
答案 0 :(得分:5)
就像你看到的一样简单..
选项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
选项2:groupby
和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
选项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
答案 1 :(得分:0)
df.groupby(['date','brand'])['red','blue','green'].count()
...或
df.groupby(['date','brand']).agg('count')