How to create pivot with totals (margins) in Pandas?

前端 未结 1 1545
春和景丽
春和景丽 2021-01-14 12:05

For example, I have a very simple data frame:

values = pd.Series(i for i in range(5))
rows = pd.Series([\'a\', \'b\', \'a\', \'a\', \'b\'])
columns = pd.date         


        
相关标签:
1条回答
  • 2021-01-14 12:42

    I can reproduce your issue. It sounds like a bug. At least I found that reassigning the column names workaround the issue:

    df.columns = ['rows', 'columns', 'values']
    
    pd.pivot_table(
        ...:     data=df,
        ...:     rows='rows',
        ...:     cols='columns',
        ...:     values='values',
        ...:     margins=True)
    Out[34]: 
    columns                     a    b  All
    rows                                   
    2013-01-01 00:00:00  0.000000  NaN    0
    2013-01-02 00:00:00       NaN  1.0    1
    2013-01-03 00:00:00  2.000000  NaN    2
    2013-01-04 00:00:00  3.000000  NaN    3
    2013-01-05 00:00:00       NaN  4.0    4
    All                  1.666667  2.5    2
    
    0 讨论(0)
提交回复
热议问题