我有以下数据:
Employee Account Currency Amount Location
Test 2 Basic USD 3000 Airport
Test 2 Net USD 2000 Airport
Test 1 Basic USD 4000 Town
Test 1 Net USD 3000 Town
Test 3 Basic GBP 5000 Town
Test 3 Net GBP 4000 Town
我可以通过执行以下操作来设法转动:
import pandas as pd
table = pd.pivot_table(df, values=['Amount'], index=['Location', 'Employee'], columns=['Account', 'Currency'], fill_value=0, aggfunc=np.sum, dropna=True)
输出:
Amount
Account Basic Net
Currency GBP USD GBP USD
Location Employee
Airport Test 2 0 3000 0 2000
Town Test 1 0 4000 0 3000
Test 3 5000 0 4000 0
Amount
Account Basic Net
Currency GBP USD GBP USD
Location Employee
Airport Test 2 0 3000 0 2000
Airport Total 3000 0 2000
Town Test 1 0 4000 0 3000
Test 3 5000 0 4000 0
Town Total 5000 4000 4000 3000
Grand Total 5000 7000 4000 5000
我试过跟随following.但它没有给出所需的输出.
谢谢.
解决方法:
您的数据透视表
table = pd.pivot_table(df, values=['Amount'],
index=['Location', 'Employee'],
columns=['Account', 'Currency'],
fill_value=0, aggfunc=np.sum, dropna=True, )
print(table)
Amount
Account Basic Net
Currency GBP USD GBP USD
Location Employee
Airport Test 2 0 3000 0 2000
Town Test 1 0 4000 0 3000
Test 3 5000 0 4000 0
pandas.concat
pd.concat([
d.append(d.sum().rename((k, 'Total')))
for k, d in table.groupby(level=0)
]).append(table.sum().rename(('Grand', 'Total')))
Amount
Account Basic Net
Currency GBP USD GBP USD
Location Employee
Airport 2 0 3000 0 2000
Total 0 3000 0 2000
Town 1 0 4000 0 3000
3 5000 0 4000 0
Total 5000 4000 4000 3000
Grand Total 5000 7000 4000 5000
老答案
为了后代
建立小计
tab_tots = table.groupby(level='Location').sum()
tab_tots.index = [tab_tots.index, ['Total'] * len(tab_tots)]
print(tab_tots)
Amount
Account Basic Net
Currency GBP USD GBP USD
Location
Airport Total 0 3000 0 2000
Town Total 5000 4000 4000 3000
全部一起
pd.concat(
[table, tab_tots]
).sort_index().append(
table.sum().rename(('Grand', 'Total'))
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。