简体   繁体   English

Pandas 数据透视表 - 向多索引表添加小计

[英]Pandas Pivot Table - Adding Subtotals to Multiindex Table

I have a table of data structured as it follows:我有一个结构如下的数据表:

Name姓名 Card卡片 Payment ID付款编号 Amount数量
John Doe约翰·多伊 t077 t077 7312637 7312637 54 54
John Doe约翰·多伊 t077 t077 1323131 1323131 34 34
Jane Doe简·多伊 s044 s044 1231321 1231321 13 13
John Doe约翰·多伊 j544 j544 4634564 4634564 53 53

The output I want to achieve is to have a pivot table with a similar format:我想要实现的输出是具有类似格式的数据透视表:

Name姓名 Number of Transactions交易数量 Sum
John Doe约翰·多伊 3 3 141 141
--- t077 --- t077 2 2 88 88
--- j544 --- j544 1 1 53 53
Jane Doe简·多伊 1 1 13 13
--- s044 --- s044 1 1 13 13

Please keep in mind that:请记住:

  • Payment ID uniquely identifies the transaction (every line in the table)付款 ID 唯一标识交易(表中的每一行)
  • Every Name can have one or multiple transactions with one or multiple cards每个名称都可以使用一张或多张卡进行一次或多次交易

I tried using pandas pivot_table, however I cannot find a way to structure the data as I want (including subtotals per Name), I can only group by Name and Card using我尝试使用pandas pivot_table,但是我找不到一种方法来按我想要的方式构造数据(包括每个名称的小计),我只能使用名称和卡片分组

pd.pivot_table(df, values='Amount', index=['Name','Card'], aggfunc=(np.sum, len))

Sorry for the poor formatting on the table, my markdown skills are quite limited.对不起,桌子上的格式很差,我的降价技能非常有限。

Any help on this?对此有什么帮助吗?

Pivot table is a good approach, try:数据透视表是一个很好的方法,试试:

table = pd.pivot_table(
    df, 
    values=['Amount'],
    index=['Name', 'Card'],
    aggfunc=['count', 'sum'],
)

# Adds subtotals, and sorts:
pd.concat([
    d.append(d.sum().rename((k, 'Total')))
    for k, d in table.groupby(level=0)
]).sort_index(ascending=[False, True])

Output:输出:

                count    sum
               Amount Amount
Name     Card
Joe Doe  Total      3    141
         j544       1     53
         t077       2     88
Jane Doe Total      1     13
         s044       1     13

Subtotal reference: link.小计参考: 链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM