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

2024-06-01 01:50:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在数据透视表中添加一个计算字段(比率)。 类似于这个问题(How to add calculated % to a pandas pivottable),我不能让我的代码工作。你知道吗

我正在努力获得电子邮件的最近开放率%。一个简单的比率,公式如下: dst['perc']=(dst['recency\u opened']/dst['recency\u 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

另外,我也可以使用数据帧(不一定是透视表),因为我真的希望分析电子邮件最近打开率。你知道吗


Tags: to数据true电子邮件typesentdst比率
1条回答
网友
1楼 · 发布于 2024-06-01 01:50:57

你是用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

相关问题 更多 >