[英]pandas pivot table: How to find count for each group in Index and Column
I am new to pivot table.我是数据透视表的新手。 I just want the count of each Age Grp by Mth.我只想按 Mth 计算每个 Age Grp 的数量。 I tried我试过
pivot1=pd.pivot_table(df,index=[ "Age Grp"], columns=["Mth"], values=["Age Grp"], aggfunc=pd.Series.nunique)
but get ValueError: Grouper for 'Age Grp' not 1-dimensional
但得到ValueError: Grouper for 'Age Grp' not 1-dimensional
DF DF
|Age Grp | Mth |
| 0-4 | 1 |
| 5 -9 | 5 |
| 0-4 | 10 |
| 10-14 | 5 |
Desired Outcome期望的结果
Mth | 1 | 5 | 10 |
|Age Grp | |
| 0-4 | 1 | 0 | 1|
| 5 -9 | 0 | 1 | 0|
| 10-14 | 0 | 1 | 0|
We can try crosstab
instead of pivot_table
with values
and an aggfunc
then use fillna
to replace the NaN
values with 0
:我们可以尝试crosstab
,而不是pivot_table
与values
和aggfunc
然后用fillna
更换NaN
使用值0
:
ct_df = pd.crosstab(
df['Age Grp'], df['Mth'],
values=df['Age Grp'], aggfunc='nunique'
).fillna(0, downcast='infer')
ct_df
: ct_df
:
Mth 1 5 10
Age Grp
0-4 1 0 1
10-14 0 1 0
5-9 0 1 0
Or with groupby nunique
+ unstack
:或与groupby nunique
+ unstack
:
df_us = df.groupby(
['Age Grp', 'Mth']
)['Age Grp'].nunique().unstack(fill_value=0)
df_us
: df_us
:
Mth 1 5 10
Age Grp
0-4 1 0 1
10-14 0 1 0
5-9 0 1 0
Setup and imports设置和导入
import pandas as pd # 1.3.4
df = pd.DataFrame({
'Age Grp': ['0-4', '5-9', '0-4', '10-14'], 'Mth': [1, 5, 10, 5]
})
Or:或者:
df.groupby(['Age Grp', 'Mth']).size().unstack(fill_value=0)
Output:输出:
Mth 1 5 10
Age Grp
0-4 1 0 1
10-14 0 1 0
5-9 0 1 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.