使用数据透视表(pandas)中的小计行时保留索引部分(不同的列)

问题描述 投票:2回答:2

我试图在数据透视表中添加小计行(使用pandas pd.pivot_table)。这是代码table = pd.pivot_table(df, values= ['Quantity', 'Money', 'Cost'], index=['house','date', 'currency', 'family name'], columns=[], fill_value=0, aggfunc=np.sum)。这是相应的输出(导出到excel):

enter image description here

然后,我尝试使用house作为参考获得小计行。我按照此链接Pivot table subtotals in Pandas中所述的步骤进行操作,因此我使用tablesum = table.groupby(level='house').sum()创建了一个组。在我尝试连接tabletablesum数据帧之前,一切似乎都很好。这就是我得到的(对于A家庭):

enter image description here

基本上,我只用一列(用逗号分隔)获得了表索引(房子,日期,货币,姓氏)中列出的四个类别。所以,即使我按房子得到小计,我也失去了pivot_table分离。所以,我的问题是:我怎样才能保留它(将pivot_table的索引保存在不同的列中)?

任何帮助将非常感谢它。

问候,

pd:我还检查了这个链接Sub Total in pandas pivot Table,但这给了我另一种与字符串和数字相关的错误。

pandas pivot-table pandas-groupby subtotal
2个回答
2
投票

您可以使用MultiIndex级别创建自定义4然后分配。

注意:第二级date必须转换为字符串,因为与字符串连接,否则得到:

TypeError:无法将类型'Timestamp'与'str'类型进行比较

df = pd.DataFrame({'house':list('aaaaabbbbb'),
                   'date':['2015-01-01'] * 3 + ['2015-01-02'] * 2 + 
                          ['2015-01-01'] * 3 +['2015-01-02'] * 2,
                   'currency':['USD'] * 3 + ['NK'] * 2 + ['USD'] * 3 +['NK'] * 2,
                   'Quantity':[1,3,5,7,1,0,7,2,3,9],
                   'Money':[5,3,6,9,2,4,7,2,3,9],
                   'Cost':[5,3,6,9,2,4,7,2,3,9],
                   'family name':list('aabbccaabb')})

print (df)
   Cost  Money  Quantity currency        date family name house
0     5      5         1      USD  2015-01-01           a     a
1     3      3         3      USD  2015-01-01           a     a
2     6      6         5      USD  2015-01-01           b     a
3     9      9         7       NK  2015-01-02           b     a
4     2      2         1       NK  2015-01-02           c     a
5     4      4         0      USD  2015-01-01           c     b
6     7      7         7      USD  2015-01-01           a     b
7     2      2         2      USD  2015-01-01           a     b
8     3      3         3       NK  2015-01-02           b     b
9     9      9         9       NK  2015-01-02           b     b

#convert only for subtotal - join with empty strings
df['date'] = df['date'].astype(str)

table = pd.pivot_table(df, values= ['Quantity', 'Money', 'Cost'], 
                       index=['house','date', 'currency', 'family name'], 
                       fill_value=0, 
                       aggfunc=np.sum)
print (table)
                                       Cost  Money  Quantity
house date       currency family name                       
a     2015-01-01 USD      a               8      8         4
                          b               6      6         5
      2015-01-02 NK       b               9      9         7
                          c               2      2         1
b     2015-01-01 USD      a               9      9         9
                          c               4      4         0
      2015-01-02 NK       b              12     12        12

tablesum = table.groupby(level='house').sum()

tablesum.index = pd.MultiIndex.from_arrays([tablesum.index.get_level_values(0)+ '_sum', 
                                            len(tablesum.index) * [''],
                                            len(tablesum.index) * [''],
                                            len(tablesum.index) * ['']])

print (tablesum)
          Cost  Money  Quantity
a_sum       25     25        17
b_sum       25     25        21

print (tablesum.index)
MultiIndex(levels=[['a_sum', 'b_sum'], [''], [''], ['']],
           labels=[[0, 1], [0, 0], [0, 0], [0, 0]])


df = pd.concat([table, tablesum]).sort_index(level=0)
print (df)
                                       Cost  Money  Quantity
house date       currency family name                       
a     2015-01-01 USD      a               8      8         4
                          b               6      6         5
      2015-01-02 NK       b               9      9         7
                          c               2      2         1
a_sum                                    25     25        17
b     2015-01-01 USD      a               9      9         9
                          c               4      4         0
      2015-01-02 NK       b              12     12        12
b_sum                                    25     25        21

0
投票

您可以使用transform将原始表布局保留在group by之后。因此,以下内容可能会为您提供所需的结果。

table.groupby(level='house').transform("sum") 

如果这不是您想要的,请澄清。

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html

© www.soinside.com 2019 - 2024. All rights reserved.