[英]pandas groupby at row and column level
My dataframe is in the below format:我的数据框采用以下格式:
col1 col2 col3
A1 B1 t1
A2 B2 t2
A1 B1 t1
A1 B2 t2
I am grouping a dataframe as below:我将数据框分组如下:
df.groupby(['col1', 'col2'])['col3'].count()
which gives me the stats as:这给了我统计数据:
A1 B1 2
A1 B2 1
A2 B2 1
What I would like the count be split on the basis of col3 like:我希望根据 col3 拆分计数,例如:
t1 t2
A1 B1 1 1
A1 B2 0 1
A2 B2 0 1
How could I achieve something like this?我怎么能做到这样的事情?
You can use a pivot_table
:您可以使用pivot_table
:
out = (df.assign(count=1)
.pivot_table(index=['col1', 'col2'], columns='col3', values='count',
aggfunc='count', fill_value=0)
)
output:输出:
col3 t1 t2
col1 col2
A1 B1 2 0
B2 0 1
A2 B2 0 1
crosstab
pd.crosstab([df['col1'], df['col2']], df['col3'])
col3 t1 t2
col1 col2
A1 B1 2 0
B2 0 1
A2 B2 0 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.