[英]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 ![]() |
7312637 ![]() |
54 ![]() |
John Doe![]() |
t077 ![]() |
1323131 ![]() |
34 ![]() |
Jane Doe![]() |
s044 ![]() |
1231321 ![]() |
13 ![]() |
John Doe![]() |
j544 ![]() |
4634564 ![]() |
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 ![]() |
141 ![]() |
--- t077 ![]() |
2 ![]() |
88 ![]() |
--- j544 ![]() |
1 ![]() |
53 ![]() |
Jane Doe![]() |
1 ![]() |
13 ![]() |
--- s044 ![]() |
1 ![]() |
13 ![]() |
Please keep in mind that:请记住:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.