如何在数据透视表中添加计算比率?

问题描述 投票:0回答:1

我想在pandas数据透视表中添加一个计算字段(比率)。类似于这个问题(How to add calculated % to a pandas pivottable)我无法使用我的代码。

我正在尝试获取电子邮件的新近度开放率%。使用如下公式的简单比率:dst ['perc'] =(dst ['recency_opened'] / dst ['recency_sent'])

 # My Pivot Table code: 
 emails = 
 pd.pivot_table(dst,'emails_opened','emails_sent','recency_opened', 
 'recency_sent', 'perc'],['segment', 'hcp_type'], aggfunc='sum', 
 fill_value=None, margins=True, dropna=True, margins_name='Total')

 emails

结果是这样的:

                perc    recency_opened  recency_sent
hcp_type            
Doctor          113.0   113             150
Nurse           33.0     33              37
Total           146.0   146             187

但我的预期结果应该是:

                perc    recency_opened  recency_sent
hcp_type            
Doctor          0.753   113             150
Nurse           0.891    33              37
Total                   146             187

另外,我也可以使用DataFrame(不一定是数据透视表),因为我真的希望分析电子邮件新近度开放率%。

python python-3.x pandas pivot-table
1个回答
0
投票

你在opened划分sent吗?

>>> import pandas as pd
>>> df = pd.DataFrame([[113, 150], [33, 37]],
                  columns=['opened', 'sent'], index=['Doctor', 'Nurse'])
>>> df['ratio (%)'] = df['opened']/df['sent']
>>> df

        opened  sent  ratio (%)
Doctor     113   150   0.753333
Nurse       33    37   0.891892
© www.soinside.com 2019 - 2024. All rights reserved.