RFM 模型是衡量客户价值和客户创利能力的重要工具和手段;
应用场景:客户关系管理(CRM) 分析模型;
指标:
- 最近一次消费 (Recency)
- 消费频率 (Frequency)
- 消费金额 (Monetary)
22.2 案例
import pandas as pd
import numpy as np
import time
data = pd.read_csv('RFM_TRAD_FLOW.csv',encoding='gbk')
# print(data)
# print(data.head())
data['time']=data['time'].map(lambda x:time.mktime(time.strptime(x,'%d%b%y:%H:%M:%S')))
# print(data)、
group_obj = data.groupby(['cumid','type'])
R = group_obj[['time']].max()
#转透视表
r_trans = pd.pivot_table(R,index='cumid',columns='type',values='time')
# print(r_trans)
r_trans[['Special_offer','returned_goods']] = r_trans[['Special_offer','returned_goods']].apply(lambda x:x.replace(np.nan,min(x)),axis=0)
# print(r_trans)
r_trans['r_max'] = r_trans[['Normal', 'Presented','Special_offer']].apply(lambda x:max(x),axis=1)
# print(r_trans)
# F
F = group_obj[['transID']].count()
print(F)
f_trans = pd.pivot_table(F,index='cumid',columns='type',values='transID')
# print(f_trans)
#
f_trans[['Special_offer','returned_goods']] = f_trans[['Special_offer','returned_goods']].fillna(0)
# print(f_trans)
f_trans['returned_goods'] = f_trans['returned_goods'].map(lambda x:-x)
# print(f_trans)
f_trans['f_total'] =f_trans.apply(lambda x:sum(x),axis=1)
print(f_trans)
# M
M = group_obj[['amount']].sum()
m_trans = pd.pivot_table(M,index='cumid',columns='type',values='amount')
# print(f_trans)
#
m_trans[['Special_offer','returned_goods']] = f_trans[['Special_offer','returned_goods']].fillna(0)
# print(f_trans)
# print(f_trans)
m_trans['m_total'] =m_trans.apply(lambda x:sum(x),axis=1)
print(m_trans)
### 合并
RFM = pd.concat([r_trans['r_max'],f_trans['f_total'],m_trans['m_total']],axis=1)
print('##################')
print(RFM)
RFM['r_score' ]= pd.cut(RFM.r_max,3,labels=[0,1,2])
RFM['f_score' ]= pd.cut(RFM.f_total,3,labels=[0,1,2])
RFM['m_score'] = pd.cut(RFM.m_total,3,labels=[0,1,2])
print(RFM)
def rfm_label(x,y,z):
if x==2 and y==2 and z==2:
return '重要价值客户'
elif x==2 and (y in [0,1]) and z ==2:
return '重要发展客户'
elif (x in [0,1]) and y==2 and z==2:
return '重要保持客户'
elif (x in [0,1] ) and (y in [0,1]) and z ==2:
return '重要挽留客户'
elif x==2 and y==2 and (z in [0,1]):
return '一般价值客户'
elif x ==2 and (y in [0,1] and (z in [0,1])):
return '一般发展客户'
elif (x in [0,1]) and y==2 and (z in [0,1]):
return '一般保持客户'
elif (x in [0,1]) and (y in [0,1]) and (z in (0,1)):
return '一般挽留客户'
RFM['标签']=RFM[[ 'r_score', 'f_score', 'm_score']].apply(lambda x:rfm_label(x[0],x[1],x[2]),axis=1)
print(RFM)
#选择满足条件的行
# pd.read_sql_query()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91