[英]Pandas Column Calculations in PivotTable
我是熊貓新手。 我創建了此數據透視表,但是我需要弄清楚如何每天僅在'is_match'值上應用函數。 有關數據頭,請參見下面的img。
我需要的是價值百分比(reward_count),對於每個應用程序(行)每一天都是如此。
即,對於日期='2015-10-22',總計(true + false)= 59,101。 正確百分比為1,080 / 59,101 = 0.018%。 對於每個日期,我只想查看此%true值來代替true / false計數。
原始數據:
date app_name is_match rewards_count
10/22/15 NFL HUDDLE 2016 FALSE 45816
10/22/15 NFL HUDDLE 2016 TRUE 1080
10/22/15 NFL HUDDLE 2016 FALSE 8
10/22/15 NFL HUDDLE 2016 FALSE 128239
10/23/15 NFL HUDDLE 2016 TRUE 908
10/23/15 NFL HUDDLE 2016 FALSE 18
10/24/15 NFL HUDDLE 2016 TRUE 638
數據框:
table = pd.pivot_table(df, index=['app_name'],
columns=['date','is_match'],
values = 'rewards_count')
非常感謝你的幫助。 我花了半天時間瀏覽Pandas文檔,但不知道我在尋找什么/要參考什么。
使用多重索引可以幫助:
table = pd.pivot_table(apps, index=['app_name', 'date'],
columns=['is_match'],
values = 'rewards_count',
aggfunc=np.sum,
margins=True)
我用aggfunc=np.sum
所有計數,並使用margins=True
計算True
和False
的總和。 這些總和以All
結尾:
is_match False True All
app_name date
NFL HUDDLE 2016 10/22/15 174063 1080 175143
10/23/15 18 908 926
10/24/15 79322 638 79960
All 253403 2626 256029
我添加了兩個包含百分比的新列:
table['percent_false'] = table[False] / table.All * 100
table['percent_true'] = table[True] / table.All * 100
結果看起來像這樣:
is_match False True All percent_false percent_true
app_name date
NFL HUDDLE 2016 10/22/15 174063 1080 175143 99.383361 0.616639
10/23/15 18 908 926 1.943844 98.056156
10/24/15 79322 638 79960 99.202101 0.797899
All 253403 2626 256029 98.974335 1.025665
桌子上有很多多余的東西。 只選擇您想要的:
percent_true = table.ix[:-1, ['percent_true']]
給出:
is_match percent_true
app_name date
NFL HUDDLE 2016 10/22/15 0.616639
10/23/15 98.056156
10/24/15 0.797899
如果您想要計數的平均值,就像您在方法中所做的那樣,請不要使用aggfunc=np.sum
。 您還需要手工總結:
table = pd.pivot_table(apps, index=['app_name', 'date'],
columns=['is_match'],
values = 'rewards_count')
table['total'] = table[False] + table[True]
table['percent_false'] = table[False] / table.total * 100
table['percent_true'] = table[True] / table.total * 100
現在結果看起來像這樣:
is_match False True total percent_false percent_true
app_name date
NFL HUDDLE 2016 10/22/15 58021 1080 59101 98.172620 1.827380
10/23/15 18 908 926 1.943844 98.056156
10/24/15 79322 638 79960 99.202101 0.797899
同樣,僅選擇相關部分:
percent_true = table[['percent_true']]
給出:
is_match percent_true
app_name date
NFL HUDDLE 2016 10/22/15 1.827380
10/23/15 98.056156
10/24/15 0.797899
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.