簡體   English   中英

按行 pivot 表占總數的百分比

[英]Percent of Total by row pivot table

我正在使用以下 function:

def pivot_count(df, rows, columns, calc_field):
    df_pivot = df.pivot_table(values=calc_field, 
                              index=rows, 
                              columns=columns, 
                              aggfunc=np.size
                             ).dropna(axis=0, how='all')
    return df_pivot

要創建一個 pivot 表,其中包含每個“calc_field”的計數,以獲得如下信息:

ProfitCluster   Affluent Customer   High Net Worth  Mass Customer
HighMargin             302                324           568
HighRevenue            301                323           645
LessProfitable         246                246           529 

我怎樣才能修改 function 得到這樣的東西:

ProfitCluster   Affluent Customer   High Net Worth  Mass Customer
HighMargin             0.25               0.27          0.47
HighRevenue            0.23               0.25          0.50
LessProfitable         0.24               0.24          0.51 

謝謝,SOA 社區。

更改為crossstab

def pivot_count(df, rows, columns, calc_field):
    df_pivot = pd.crossstab(values=df[calc_field], 
                              index=df[rows], 
                              columns=df[columns], 
                              normalize='index',
                              aggfunc=np.size
                             )
    return df_pivot

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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