Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # В данных о заказах и расходах выделим из дат столбцы с информацией о месяце.
- orders['order_month'] = orders['buy_ts'].astype('datetime64[M]')
- costs['month'] = costs['dt'].astype('datetime64[M]')
- # Выделим в данных о заказах помесячные когорты покупателей
- # Выделим месяц первой покупки каждого покупателя
- first_orders = orders.groupby('uid').agg({'order_month': 'min'}).reset_index()
- first_orders.columns = ['uid', 'first_order_month']
- # добавим в данные месяц первой покупки в первоначальную таблицу с заказами
- orders_new = pd.merge(orders,first_orders, on='uid')
- # Посчитаем количество новых покупателей каждый месяц
- cohort_sizes = first_orders.groupby('first_order_month').agg({'uid': 'nunique'}).reset_index()
- cohort_sizes.columns = ['first_order_month', 'buyers_nmb']
- # посчитаем выручку по когортам
- cohorts = orders_new.groupby(['first_order_month','order_month']).agg({'revenue': 'sum'}).reset_index()
- # добавим в таблицу с выручкой по когортам данные о размере когорт, т.е. о ежемесячном количестве новых покупателей
- report = pd.merge(cohort_sizes, cohorts, on='first_order_month')
- margin_rate = 0.5
- report['gross_profit'] = report['revenue'] * margin_rate
- # добавим данные о сроке жизни когорты на каждый месяц заказа
- report['age'] = (report['order_month'] - report['first_order_month']) / np.timedelta64(1, 'M')
- report['age'] = report['age'].round().astype('int')
- # оставим в столбце с когортами только год и месяц
- report['first_order_month'] =report['first_order_month'].dt.strftime('%Y.%m')
- report['ltv'] = report['gross_profit'] / report['buyers_nmb']
- output = report.pivot_table(index='first_order_month', columns='age', values='ltv', aggfunc='mean')
- plt.figure(figsize=(13, 9))
- plt.title('LTV когорт по месяцам')
- ax = sns.heatmap(output, annot=True, fmt='.2f', linewidths=1, linecolor='gray')
- ax.set_ylabel('Месяц когорты')
- ax.set_xlabel('Месяц жизни когорты')
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement