# RFM Analysis with Python

RFM analysis is a marketing technique used to quantitatively determine who the best customers are by looking at what date a customer bought (recency), how often they buy (frequency) and how much the customer is spending (in money). In RFM analysis, RFM stands for recency, frequency, and monetary.

## RFM Analysis

In this article, I will introduce you to a data science task on RFM analysis using Python. Let’s do an RFM analysis using retail data. It contains customer-level data on transactions by date. He also obtained information on responses to a promotional campaign conducted by the organization. Now let’s start with importing the necessary libraries:

Also, Read – GroupBy Function in Python Pandas.

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt``````

The dataset, I am using in this task can be downloaded from here. Now let’s read the dataset using the pandas package in python:

``````df = pd.read_csv('Retail_Data_Transactions.csv', parse_dates=['trans_date'])
``````

Suppose the study is performed from 01 / April / 2015. We will identify the oldest and most recent transaction dates:

``````print(df['trans_date'].min(), df['trans_date'].max())
``````
`2011-05-16 00:00:00 2015-03-16 00:00:00`

The number of days from the date of the study is calculated as below:

``````sd = dt.datetime(2015,4,1)
df['hist']=sd - df['trans_date']
df['hist'].astype('timedelta64[D]')
df['hist']=df['hist'] / np.timedelta64(1, 'D')``````

Only transactions carried out in the last 2 years are taken into account for the RFM analysis:

``df=df[df['hist'] < 730]``

The data will be summarized at the customer level by taking the number of days until the last transaction, the sum of the total transaction amount and the total transaction number:

``````rfmTable = df.groupby('customer_id').agg({'hist': lambda x:x.min(), # Recency
'customer_id': lambda x: len(x),               # Frequency
'tran_amount': lambda x: x.sum()})          # Monetary Value

rfmTable.rename(columns={'hist': 'recency',
'customer_id': 'frequency',
'tran_amount': 'monetary_value'}, inplace=True)``````

RFM analysis consists of classifying R, F and M into 3 or more categories. For simplicity, I will create 4 categories based on the quartiles:

``quartiles = rfmTable.quantile(q=[0.25,0.50,0.75])``

let’s convert the quartile information into a dictionary so that the thresholds can be raised:

``quartiles=quartiles.to_dict()``

In the case of recency, the lower the better and therefore our categorization system must be reversed:

``````def RClass(x,p,d):
if x <= d[p][0.25]:
return 1
elif x <= d[p][0.50]:
return 2
elif x <= d[p][0.75]:
return 3
else:
return 4

## for Frequency and Monetary value

def FMClass(x,p,d):
if x <= d[p][0.25]:
return 4
elif x <= d[p][0.50]:
return 3
elif x <= d[p][0.75]:
return 2
else:
return 1
rfmSeg = rfmTable
rfmSeg['R_Quartile'] = rfmSeg['recency'].apply(RClass, args=('recency',quartiles,))
rfmSeg['F_Quartile'] = rfmSeg['frequency'].apply(FMClass, args=('frequency',quartiles,))
rfmSeg['M_Quartile'] = rfmSeg['monetary_value'].apply(FMClass, args=('monetary_value',quartiles,))``````

For RFM analysis, it is essential to combine scores to create a single score. There are a few approaches. One simple way is to join the scores to create a 3-digit number between 111 and 444. The downside here is too many categories (4x4x4). Also, not easy to prioritize scores like 421 versus 412:

``````rfmSeg['RFMClass'] = rfmSeg.R_Quartile.map(str)
+ rfmSeg.F_Quartile.map(str)
+ rfmSeg.M_Quartile.map(str)
rfmSeg.sort_values(by=['RFMClass', 'monetary_value'], ascending=[True, False])
``````

Another possibility is to combine the scores to create a score (eg 4 + 1 + 1). Here the advantage is that each of the scores has the same importance. However, some scores will have many locations as constituents (eg – 413 and 431):

``rfmSeg['Total Score'] = rfmSeg['R_Quartile'] + rfmSeg['F_Quartile'] +rfmSeg['M_Quartile']``

Let’s check how the combined score arranges R, F and M:

``rfmSeg.groupby('Total Score').agg('monetary_value').mean().plot(kind='bar', colormap='Blues_r')``
``````rfmSeg.groupby('Total Score').agg('frequency').mean().plot(kind='bar', colormap='Blues_r')
``````

The ultimate test of the RFM analysis is the impact on any consumer behaviour. Let’s check its impact on customer response to a promotional campaign:

``````res = pd.read_csv('../input/Retail_Data_Response.csv')
res.sort_values('customer_id', inplace=True)
rfmSeg.reset_index(inplace=True)
rfmSeg.sort_values('customer_id', inplace=True)
rfm2=pd.merge(rfmSeg, res, on='customer_id')

ax=rfm2.groupby('Total Score').agg('response').mean().plot(kind='bar', colormap='copper_r')
ax.set_xlabel("Total Score")
ax.set_ylabel("Proportion of Responders")``````

The graph shows that response behaviour is strongly related to the combined score. However, there is not much difference between scores of 3,4.5 and 6. While the performance of RFM scores is much lower for scores greater than 6.

Also, Read – Lung Segmentation with Machine Learning.

I hope you liked this article on a Data Science task on RFM analysis using python. Feel free to ask you valuable questions in the comments section below. You can also follow me on Medium to learn every topic of Data Science and Machine Learning.
{"ft_lang_label":"__label__en","ft_lang_prob":0.74298126,"math_prob":0.89613575,"size":5137,"snap":"2020-45-2020-50","text_gpt3_token_len":1364,"char_repetition_ratio":0.113578804,"word_repetition_ratio":0.014705882,"special_character_ratio":0.2703913,"punctuation_ratio":0.17,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99040735,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-26T06:37:13Z\",\"WARC-Record-ID\":\"<urn:uuid:b422c23d-8788-4ca6-bcf4-4d0953e22246>\",\"Content-Length\":\"161558\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:19da179f-9cfd-43d5-a202-bcf0b58725f1>\",\"WARC-Concurrent-To\":\"<urn:uuid:0f7ce3de-6c12-4501-b484-01cf803a6b3d>\",\"WARC-IP-Address\":\"192.0.78.224\",\"WARC-Target-URI\":\"https://thecleverprogrammer.com/2020/09/07/rfm-analysis-with-python/\",\"WARC-Payload-Digest\":\"sha1:LF63CC5HVCEM7OB27N2DZIKSRU5SMZS6\",\"WARC-Block-Digest\":\"sha1:IQAIK6P34DKTF4NSO23OTXALNFVBUPJW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107890586.57_warc_CC-MAIN-20201026061044-20201026091044-00114.warc.gz\"}"}