• 【python笔记】客户运营 - cohort分析


    一、数据

    本文涉及数据下载链接

    二、数据预处理

    2.1 读取数据

    import pandas as pd
    
    df = pd.read_csv('your_path/Year 2010-2011.csv', encoding='ISO-8859-1')
    df.head()
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    2.2 检查数据

    • 检查空值情况
    df.isna().sum() 
    # 结果
    Invoice             0
    StockCode           0
    Description      1454
    Quantity            0
    InvoiceDate         0
    Price               0
    Customer ID    135080
    Country             0
    dtype: int64
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 检查重复情况
    df.duplicated().sum()
    # 结果
    5268
    
    • 1
    • 2
    • 3
    • 检查数值分布
    df.describe()
    
    • 1

    df.describe()

    2.3 小结:进行数据预处理

    df = df.drop_duplicates()
    df = df.dropna()
    df = df.query('Quantity>0 & Price>0')
    
    • 1
    • 2
    • 3

    三、可视化

    3.1 把时间调整成月份

    df['date_new'] = df['InvoiceDate'].copy()
    df['date_new'] = pd.to_datetime(df.date_new, format='%m/%d/%Y %H:%M')
    df['yyyymm'] = df.date_new.dt.to_period('M')
    
    • 1
    • 2
    • 3

    3.2 获取所需字段

    df['start_month'] = df.groupby('Customer ID')['yyyymm'].transform(min)
    df['lasted_months'] = (df.yyyymm- df.start_month).apply(lambda x: x.n)
    
    print(df.head())
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    3.3 做成客户留存表

    pt = df.pivot_table(index='start_month', columns='lasted_months', values='Customer ID', aggfunc='nunique')
    pt_cohort = pt.divide(pt.iloc[:,0], axis=0)
    
    print(pt_cohort.head(2))
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    3.4 做成热力图

    import seaborn as sns
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    
    with sns.axes_style('white'):
        plt.rcParams['font.family'] = 'simhei'
        fig, axes = plt.subplots(1, 2, figsize=(12, 8), 
        						sharey=True, 
        						gridspec_kw={'width_ratios': [1, 11]})
    
        sns.heatmap(pt_cohort, annot=True, fmt='.0%', ax=axes[1])
        axes[1].set_title('月度Cohorts: 客户留存', fontsize=16)
        axes[1].set(xlabel='# of periods', ylabel='')
    
        sns.heatmap(pd.DataFrame(pt.iloc[:,0]),
                    annot=True, fmt='g',
                    cbar=False,
                    cmap=mcolors.ListedColormap('white'),
                    ax=axes[0])
        fig.tight_layout()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

  • 相关阅读:
    经典面试题-volatile的作用
    使用 shell 脚本自动申请进京证 (六环外) —— debug 过程
    maven打包时,如何构建docker镜像,并推送到私有docker仓库
    C++二分查找算法:阶乘函数后 K 个零
    【matplotlib基础】--几何图形
    计算机毕业设计SSM电影院购票系统【附源码数据库】
    Java自学day5
    德语翻译器在线翻译中文-德语翻译器支持各大语言翻译
    计算机网络分类
    python内置函数
  • 原文地址:https://blog.csdn.net/htuhxf/article/details/134521440