首页 > 解决方案 > pandas pivot_table Margin=True 的问题没有给我正确的答案

问题描述

pd.pivot_table(subset_one,index=["Institution_Types"],values=["Current_Balance"],aggfunc=([len, np.mean, max, min]),\ margins=True, margins_name='Total').reset_index()\ .rename(columns={'len': 'Loan Count', 'mean':'Average', 'max':'Max','min':'Min'})

总列没有给出正确答案。查看我的结果

标签: pythonpandas

解决方案


或者,您可以尝试使用数据透视表,Margin=False然后添加一行Total,如下所示:

pd.pivot_table(
    subset_one,
    index=["Institution_Types"],
    values=["Current_Balance"],
    aggfunc=([len, np.mean, max, min]),
    margins=False,
).reset_index().rename(
    columns={"len": "Loan Count", "mean": "Average", "max": "Max", "min": "Min"}
)
df = df.append(df.sum(axis=0), ignore_index=True)
df.iloc[-1, 0] = "Total"

推荐阅读