数据透视表熊猫
问题描述:
我的问题是编辑每个类别的小计,并显示总数,然后编辑列“全部”,但我不能这样做。 请告诉我如何继续请。 prets_preview的链接文件:http://www.cjoint.com/c/GBijO4uZYjt 和issues_out:http://www.cjoint.com/c/GBsm0IXIILE 感谢您的帮助。数据透视表熊猫
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: from pandas import DataFrame
In [4]: issues=pd.read_table('prets_preview.csv')
In [5]: site={'BUS1A' : 'Zèbre', 'MED0A' : 'Collectivités'}
In [6]: issues ['localisation'] = issues['localisation'].map(site)
In [7]: issues ['localisation'] = issues['localisation'].fillna('Médiathèque')
In [8]: resultat = issues ['id_exemplaire'].groupby([issues['localisation'],issues.ccode, issues['support']]).count()
In [9]: table = pd.pivot_table(issues,values=['id_exemplaire'], index=['locali sation'], columns =['support'], aggfunc =np.sum,margins = True)
In [10]: resultat = table.stack('support')
In [11]: resultat.to_csv('issues_out.csv')
In [12]: resultat = issues['id_exemplaire'].groupby(issues['localisation'])
.count()
In [13]: resultat = issues['id_exemplaire'].groupby([issues['localisation'], is ues['support'], issues['ccode']]).count()
In [16]: table = pd.pivot_table (issues, values=['id_exemplaire'], index=['localisation'], columns=['support'], aggfunc= np.sum, margins = True)
我需要更清楚地显示小计和编辑栏“全部”,但我不知道该怎么办。
**id_exemplaire
localisation support
Collectivités All 300390.0
DVD 0.0
Disque compact 0.0
Disque microsillon 0.0
Livre 300390.0
Livre en gros caractères 0.0
Livre sonore 0.0
Périodique 0.0
Médiathèque All 23610694.0
DVD 3710341.0
Disque compact 1684356.0
Disque microsillon 338976.0
Livre 15731162.0
Livre en gros caractères 514064.0
Livre sonore 595185.0
Périodique 1036610.0
Zèbre All 800167.0
DVD 192799.0
Disque compact 0.0
Disque microsillon 0.0
Livre 607368.0
Livre en gros caractères 0.0
Livre sonore 0.0
Périodique 0.0
All All 24711251.0
DVD 3903140.0
Disque compact 1684356.0
Disque microsillon 338976.0
Livre 16638920.0
Livre en gros caractères 514064.0
Livre sonore 595185.0
Périodique 1036610.0**
答
只需使用的pandas.pivot_table
的margins_name参数重命名默认全部标签。
table = pd.pivot_table(issues,
values = ['id_exemplaire'],
index = ['localisation'],
columns = ['support'],
aggfunc = np.sum,
margins = True,
margins_name = 'Total')
resultat = table.stack('support')
print(resultat)
输出(采用发布链接的数据)
id_exemplaire
localisation support
BUS1A DVD 192799.0
Livre 607368.0
Total 800167.0
MED0A Livre 300390.0
Total 300390.0
MED1A DVD 3710341.0
Livre 8242130.0
Livre en gros caractères 514064.0
Périodique 862281.0
Total 13328816.0
MED2A Livre 7489032.0
Livre sonore 595185.0
Périodique 174329.0
Total 8258546.0
MED3A Disque compact 1462267.0
Disque microsillon 338976.0
Total 1801243.0
MED3C Disque compact 222089.0
Total 222089.0
Total DVD 3903140.0
Disque compact 1684356.0
Disque microsillon 338976.0
Livre 16638920.0
Livre en gros caractères 514064.0
Livre sonore 595185.0
Périodique 1036610.0
Total 24711251.0
*我需要更清楚地显示小计和编辑的“全部”列* ......请告诉我们期望的结果这可以用许多方式来解释。 – Parfait
我想将“ALL”列重新命名。例如:全部 - >总计我是法国人,我需要重命名此专栏。 –