RFM分析是根据客户活跃程度和交易金额贡献,进行客户价值细分的一种方法;
可以通过R,F,M三个维度,将客户划分为8种类型。
RFM分析过程
1.计算RFM各项分值
R_S,距离当前日期越近,得分越高,最高5分,最低1分
F_S,交易频率越高,得分越高,最高5分,最低1分
M_S,交易金额越高,得分越高,最高5分,最低1分
2.归总RFM分值
RFM=100*R_S+10*F_S+1*M_S
3.根据RFM分值对客户分类
RFM分析前提,满足以下三个假设,这三个假设也是符合逻辑的
1.最近有过交易行为的客户,再次发生交易的可能性要高于最近买有交易行为的客户;
2.交易频率较高的客户比交易频率较低的客户,更有可能再次发生交易行为;
3.过去所有交易总金额较多的客户,比交易总金额较少的客户,更有消费积极性。
我们了解了RFM的分析原理后,下面来看看如何在Python中用代码实现:
import numpy
import pandas
data = pandas.read_csv(
'D:\\PDA\\5.7\\data.csv'
)
data['DealDateTime'] = pandas.to_datetime(
data.DealDateTime,
format='%Y/%m/%d'
)
data['DateDiff'] = pandas.to_datetime(
'today'
) - data['DealDateTime']
data['DateDiff'] = data['DateDiff'].dt.days
R_Agg = data.groupby(
by=['CustomerID']
)['DateDiff'].agg({
'RecencyAgg': numpy.min
})
F_Agg = data.groupby(
by=['CustomerID']
)['OrderID'].agg({
'FrequencyAgg': numpy.size
})
M_Agg = data.groupby(
by=['CustomerID']
)['Sales'].agg({
'MonetaryAgg': numpy.sum
})
aggData = R_Agg.join(F_Agg).join(M_Agg)
bins = aggData.RecencyAgg.quantile(
q=[0, 0.2, 0.4, 0.6, 0.8, 1],
interpolation='nearest'
)
bins[0] = 0
labels = [5, 4, 3, 2, 1]
R_S = pandas.cut(
aggData.RecencyAgg,
bins, labels=labels
)
bins = aggData.FrequencyAgg.quantile(
q=[0, 0.2, 0.4, 0.6, 0.8, 1],
interpolation='nearest'
)
bins[0] = 0;
labels = [1, 2, 3, 4, 5];
F_S = pandas.cut(
aggData.FrequencyAgg,
bins, labels=labels
)
bins = aggData.MonetaryAgg.quantile(
q=[0, 0.2, 0.4, 0.6, 0.8, 1],
interpolation='nearest'
)
bins[0] = 0
labels = [1, 2, 3, 4, 5]
M_S = pandas.cut(
aggData.MonetaryAgg,
bins, labels=labels
)
aggData['R_S']=R_S
aggData['F_S']=F_S
aggData['M_S']=M_S
aggData['RFM'] = 100*R_S.astype(int) + 10*F_S.astype(int) + 1*M_S.astype(int)
bins = aggData.RFM.quantile(
q=[
0, 0.125, 0.25, 0.375, 0.5,
0.625, 0.75, 0.875, 1
],
interpolation='nearest'
)
bins[0] = 0
labels = [1, 2, 3, 4, 5, 6, 7, 8]
aggData['level'] = pandas.cut(
aggData.RFM,
bins, labels=labels
)
aggData = aggData.reset_index()
aggData.sort(
['level', 'RFM'],
ascending=[1, 1]
)
aggData.groupby(
by=['level']
)['CustomerID'].agg({
'size':numpy.size
})