← Back to case study

PROJECT 062 · PYTHON SOURCE

Returning and new visitor behavior

Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.

Download Python file ↓
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute

META = {'id': 62, 'dataset': 'shoppers', 'title': 'Returning and new visitor behavior', 'question': 'Do recorded visitor types differ in purchase conversion and product engagement?', 'method': 'Conversion intervals joined to median product-page engagement.', 'action': 'Separate retention and acquisition hypotheses before designing an experiment.', 'limitations': 'One observation is a completed session. End-of-session behavior cannot support an early-session prediction claim. PageValues is excluded from purchase models because it can encode downstream purchase information. Associations are not experiment results. '}

def analyze():
    df = load('shoppers').copy()
    t=rates(df,'visitortype','revenue')
    t=t.merge(df.groupby('visitortype').agg(median_product_pages=('productrelated','median'),median_product_seconds=('productrelated_duration','median')).reset_index(),on='visitortype')
    out=result(t,'visitortype','rate','Purchase-session share','Visitor labels do not identify individual customers or lifetime value.')
    return out

if __name__ == "__main__":
    execute(Path(__file__).parent, META, analyze)