【问题标题】:Why i am not getting the subtotal of rows为什么我没有得到行的小计
【发布时间】:2019-03-28 01:20:02
【问题描述】:

我正在尝试使用 pandas 旋转来获得小计。我不知道为什么我只得到列小计?


    data = {'TypeOfInvestor':['Stocks', 'Bonds', 'Real Estate'],
            'InvestorA': [96, 181, 88],
           'InvestorB': [185, 3, 152],
           'InvestorC': [39, 29, 142]}






      df = pd.DataFrame(data)


    pt = pd.pivot_table(df, values=['InvestorA', 'InvestorB', 'InvestorC'],
                        index=['TypeOfInvestor'],
                   aggfunc=np.sum, margins=True, margins_name='Total')

我希望使用 pivot_table 获得列的小计和行的小计,但我只得到列的小计。

【问题讨论】:

    标签: pandas crosstab subtotal


    【解决方案1】:

    您可以通过使用.sumaxis=1 来轻松添加:

    pt['Total']= pt.sum(axis=1)
    
    print(pt)
                    InvestorA  InvestorB  InvestorC  Total
    TypeOfInvestor                                        
    Bonds                 181          3         29    213
    Real Estate            88        152        142    382
    Stocks                 96        185         39    320
    Total                 365        340        210    915
    

    【讨论】:

    • 谢谢@Erfan 我会接受答案,因为它完成了工作,但我不明白为什么在使用 pandas pivot 时这种类型的数据集只有列小计。
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 2013-07-15
    • 2015-06-03
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多