I wish to add a calculated field (a ratio) to a pandas pivot table. Similar to this question (How to add calculated % to a pandas pivottable) I could not have my code to work.
I am trying to get the recency open rate % for emails. A simple ratio with a formula shown below: 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
The result is this:
perc recency_opened recency_sent
hcp_type
Doctor 113.0 113 150
Nurse 33.0 33 37
Total 146.0 146 187
But my expected result should be:
perc recency_opened recency_sent
hcp_type
Doctor 0.753 113 150
Nurse 0.891 33 37
Total 146 187
Alternativelly, I could also get by with a DataFrame (not necessarily a pivot table) because I just really wish to analyse the email recency open rate%.