[英]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.