Untitled

From Stained Pudu, 2 Months ago, written in Plain Text, viewed 56 times.
URL http://codebin.org/view/ccdf0779 Embed
Download Paste or View Raw
  1. # функция для создания пользовательских профилей
  2.  
  3. def get_profiles(sessions, orders, events, ad_costs, event_names=[]):
  4.  
  5.     # находим параметры первых посещений
  6.     profiles = (
  7.         sessions.sort_values(by=['user_id', 'session_start'])
  8.         .groupby('user_id')
  9.         .agg(
  10.             {
  11.                 'session_start': 'first',
  12.                 'channel': 'first',
  13.                 'device': 'first',
  14.                 'region': 'first',
  15.             }
  16.         )
  17.         .rename(columns={'session_start': 'first_ts'})
  18.         .reset_index()
  19.     )
  20.  
  21.     # для когортного анализа определяем дату первого посещения
  22.     # и первый день месяца, в который это посещение произошло
  23.     profiles['dt'] = profiles['first_ts'].dt.date
  24.     profiles['month'] = profiles['first_ts'].astype('datetime64[M]')
  25.  
  26.     # добавляем признак платящих пользователей
  27.     profiles['payer'] = profiles['user_id'].isin(orders['user_id'].unique())
  28.  
  29.     # добавляем флаги для всех событий из event_names
  30.     for event in event_names:
  31.         if event in events['event_name'].unique():
  32.             profiles[event] = profiles['user_id'].isin(
  33.                 events.query('event_name == @event')['user_id'].unique()
  34.             )
  35.  
  36.     # считаем количество уникальных пользователей
  37.     # с одинаковыми источником и датой привлечения
  38.     new_users = (
  39.         profiles.groupby(['dt', 'channel'])
  40.         .agg({'user_id': 'nunique'})
  41.         .rename(columns={'user_id': 'unique_users'})
  42.         .reset_index()
  43.     )
  44.  
  45.     # объединяем траты на рекламу и число привлечённых пользователей
  46.     ad_costs = ad_costs.merge(new_users, on=['dt', 'channel'], how='left')
  47.  
  48.     # делим рекламные расходы на число привлечённых пользователей
  49.     ad_costs['acquisition_cost'] = ad_costs['costs'] / ad_costs['unique_users']
  50.  
  51.     # добавляем стоимость привлечения в профили
  52.     profiles = profiles.merge(
  53.         ad_costs[['dt', 'channel', 'acquisition_cost']],
  54.         on=['dt', 'channel'],
  55.         how='left',
  56.     )
  57.  
  58.     # стоимость привлечения органических пользователей равна нулю
  59.     profiles['acquisition_cost'] = profiles['acquisition_cost'].fillna(0)
  60.  
  61.     return profiles
  62.  

Reply to "Untitled"

Here you can reply to the paste above