簡體   English   中英

pandas 數據透視表:如何在索引和列中查找每個組的計數

[英]pandas pivot table: How to find count for each group in Index and Column

我是數據透視表的新手。 我只想按 Mth 計算每個 Age Grp 的數量。 我試過

pivot1=pd.pivot_table(df,index=[ "Age Grp"], columns=["Mth"], values=["Age Grp"], aggfunc=pd.Series.nunique)

但得到ValueError: Grouper for 'Age Grp' not 1-dimensional

DF

 |Age Grp | Mth  | 
 | 0-4    |  1   |  
 | 5 -9   | 5    |  
 | 0-4    | 10   | 
 | 10-14  | 5  |  

期望的結果

     Mth  |  1    | 5 | 10 |
 |Age Grp |                |
 | 0-4    |  1   |   0  | 1|
 | 5 -9   | 0    |   1  | 0|
 | 10-14  |  0   |   1  | 0|

我們可以嘗試crosstab ,而不是pivot_tablevaluesaggfunc然后用fillna更換NaN使用值0

ct_df = pd.crosstab(
    df['Age Grp'], df['Mth'],
    values=df['Age Grp'], aggfunc='nunique'
).fillna(0, downcast='infer')

ct_df :

Mth      1   5   10
Age Grp            
0-4       1   0   1
10-14     0   1   0
5-9       0   1   0

或與groupby nunique + unstack

df_us = df.groupby(
    ['Age Grp', 'Mth']
)['Age Grp'].nunique().unstack(fill_value=0)

df_us

Mth      1   5   10
Age Grp            
0-4       1   0   1
10-14     0   1   0
5-9       0   1   0

設置和導入

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]
})

或者:

df.groupby(['Age Grp', 'Mth']).size().unstack(fill_value=0)

輸出:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM