温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么利用Python进行客户分群分析

发布时间:2023-02-24 10:37:50 来源:亿速云 阅读:113 作者:iii 栏目:开发技术

这篇文章主要讲解了“怎么利用Python进行客户分群分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么利用Python进行客户分群分析”吧!

导入数据和python库

import pandas as pd  
import matplotlib.pyplot as plt  
import seaborn as sns  
df = pd.read_csv('sales_2018-01-01_2019-12-31.csv')  
df

怎么利用Python进行客户分群分析

分离新老客户

first_time = df.loc[df['customer_type'] == 'First-time',]  
final = df.loc[df['customer_id'].isin(first_time['customer_id'].values)]

在这里,不能简单地选择df.loc[df['customer_type']],因为在这个数据中,在customer_type列下,First_time指的是新客户,而Returning指的是老客户。因此,如果我在2019年12月31日第一次购买,数据会显示我在2019年12月31日是新客户,但在我第二次、第三次…时是返回客户。同期群分析着眼于新客户和他们的后续购买行为。因此,如果我们简单地使用df.loc[df['customer_type']=='First-time',],我们就会忽略新客户的后续购买,这不是分析同期群行为的正确方法。

因此,这里所需要做的是,首先创建一个所有第一次的客户列表,并将其存储为first_time。然后从原始客户数据框df中只选择那些ID在first_time客户组内的客户。通过这样做,我们可以确保我们获得的数据只有第一次的客户和他们后来的购买行为。

现在,我们删除customer_type列,因为它已经没有必要了。同时,将日期列转换成正确的日期时间格式

final = final.drop(columns = ['customer_type'])  
final['day']= pd.to_datetime(final['day'], dayfirst=True)

按客户ID排序,然后是日期

final = final.drop(columns = ['customer_type'])  
final['day']= pd.to_datetime(final['day'], dayfirst=True)

怎么利用Python进行客户分群分析

定义一些函数

def purchase_rate(customer_id):  
    purchase_rate = [1]  
    counter = 1  
    for i in range(1,len(customer_id)):  
          if customer_id[i] != customer_id[i-1]:  
                 purchase_rate.append(1)  
                 counter = 1  
          else:  
                 counter += 1  
                 purchase_rate.append(counter)  
    return purchase_rate  
def join_date(date, purchase_rate):  
    join_date = list(range(len(date)))  
    for i in range(len(purchase_rate)):   
          if purchase_rate[i] == 1:  
                 join_date[i] = date[i]  
          else:  
                 join_date[i] = join_date[i-1]  
    return join_date  
def age_by_month(purchase_rate, month, year, join_month, join_year):  
    age_by_month = list(range(len(year)))  
    for i in range(len(purchase_rate)):  
          if purchase_rate[i] == 1:  
              age_by_month[i] = 0  
          else:  
              if year[i] == join_year[i]:  
                 age_by_month[i] = month[i] - join_month[i]  
              else:  
                 age_by_month[i] = month[i] - join_month[i] + 12*(year[i]-join_year[i])  
     return age_by_month
  • purchase_rate函数将决定这是否是每个客户的第二次、第三次、第四次购买。

  • join_date函数允许确定客户加入的日期。

  • age_by_month函数提供了从客户当前购买到第一次购买的多少个月。

现在输入已经准备好了,接下来创建群组。

创建群组

final['month'] =pd.to_datetime(final['day']).dt.month  
final['Purchase Rate'] = purchase_rate(final['customer_id'])  
final['Join Date'] = join_date(final['day'], final['Purchase Rate'])  
final['Join Date'] = pd.to_datetime(final['Join Date'], dayfirst=True)  
final['cohort'] = pd.to_datetime(final['Join Date']).dt.strftime('%Y-%m')  
final['year'] = pd.to_datetime(final['day']).dt.year  
final['Join Date Month'] = pd.to_datetime(final['Join Date']).dt.month  
final['Join Date Year'] = pd.to_datetime(final['Join Date']).dt.year

怎么利用Python进行客户分群分析

final['Age by month'] = age_by_month(final['Purchase Rate'],   
                                     final['month'],  
                                     final['year'],  
                                     final['Join Date Month'],  
                                     final['Join Date Year'])

怎么利用Python进行客户分群分析

cohorts = final.groupby(['cohort','Age by month']).nunique()  
cohorts = cohorts.customer_id.to_frame().reset_index()   # convert series to frame  
cohorts = pd.pivot_table(cohorts, values = 'customer_id',index = 'cohort', columns= 'Age by month')  
cohorts.replace(np.nan, '',regex=True)

怎么利用Python进行客户分群分析

**如何解释这个表格:**以群组2018-01为例。在2018年1月,有462名新客户。在这462人中,121名客户在2018年2月回来购买,125名在2018年3月购买,以此类推。

转换为群组百分比

for i in range(len(cohorts)-1):  
    cohorts[i+1] = cohorts[i+1]/cohorts[0]  
cohorts[0] = cohorts[0]/cohorts[0]

怎么利用Python进行客户分群分析

可视化

cohorts_t = cohorts.transpose()  
cohorts_t[cohorts_t.columns].plot(figsize=(10,5))  
sns.set(style='whitegrid')  
plt.figure(figsize=(20, 15))  
plt.title('Cohorts: User Retention')  
sns.set(font_scale = 0.5) # font size  
sns.heatmap(cohorts, mask=cohorts.isnull(),  
cmap="Blues",  
annot=True, fmt='.01%')  
plt.show()

怎么利用Python进行客户分群分析

怎么利用Python进行客户分群分析

感谢各位的阅读,以上就是“怎么利用Python进行客户分群分析”的内容了,经过本文的学习后,相信大家对怎么利用Python进行客户分群分析这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI