Introduction
Eighty percent of our business comes from 20% of our clients.
Costs 10 times less to sell to an existing customer than to find a new customer
T

In our indexThe "Index" It is a fundamental tool in books and documents, which allows you to quickly locate the desired information. Generally, it is presented at the beginning of a work and organizes the contents in a hierarchical manner, including chapters and sections. Its correct preparation facilitates navigation and improves the understanding of the material, making it an essential resource for both students and professionals in various areas.... of shares, NIFTY 50 defines how our stock market is performing similarly, in business, it is important to understand who your top customers are who provide consistent and growing revenue streams for your business.
One of the simple and effective methodologies generally used to calculate customer value over a period of time is RFM, What is it,
Recency (R): how recently a customer has made a purchase
Frequency (F): how often a customer makes a purchase
Monetary value (M): dollar value of purchases
We'll dive a little deeper into RFM analysis in the next section:
Let's take a small example where a bank wants to identify key customers for retention / developing / acquisition.
Then, in the previous scenario, we need to rate each customer who had recent transactions with the bank on three important metrics mentioned above R, F y M. Later, create a qualification methodology to segment the customer base and apply for different marketing programs.
RFM analysis process
Let's calculate the RFM score for 5 sample clients,
Paso 1: Derive R, F & M of the bank's transactions in the last year.
Preferably, RFM is done for recent data and will be updated quarterly / semi-annually depending on the business

Find R, F and M is pretty simple. Let's say a customer deposited 10 K of money the 1 May and deposited other 5 K the 10 June and if you are doing an RFM analysis the 1 of July. Now for this client, the seniority will be 1 month because the last transaction was in June and the frequency will be 2 because you made two deposits in May and June and M will be 15 K
Paso 2: Get the score for each customer based on each parameter based on the range within the parameter
Para Recency, the smaller, best, due to customer, we are on your mind and for Frequency & Monitor and larger values are better

Let's take the above table as an example, when compared to all customers, seniority is better for the customer 3, since it is classified as the number 1, while for the frequency it is in the 4th position and, in terms of value, in 2nd position.
Paso 3: Standardize the score of each client based on each parameter (0-100)

Standardize = current value / Max (Value) * 100
Paso 4: Derive weighted score via each parameter for each customer
Consolidated score = 0.15 * R + 0.28 * F + 0.57 * M
Weights can be applied equally or we can provide specific weights for each parameter based on domain knowledge or business input. Here, in the previous case, We are giving more importance to Frequency and Monitoring.

We simply apply those weights to each client.
For instance,
Customer value 4 = 0,15 * 40 + 0,28 * 60 + 0,57 * 60 = 57
Later, we segregate the score into three segments,
- 0 – 50 – Low value customer
- 50 – 75 – Mid-value customer
- 76-100 – High value customer
Now, based on previous scores, a company can apply the differentiation strategy as retention / developing / acquisition of different customer segments
What's more, most of us can profile these segments with additional characteristics such as demographics, spending pattern and various products, etc. understand them a little deeper.
Now let's try to implement this RFM analysis in Python.
RMF Analysis in Python
This is a case study, where we are using a dataset from the European retail chain.
The sample data is as follows:

For our RFM analysis, the important key features we will use are InvoicDate, CustomerID and for sales, we use Quantity and Unit Price
# Import Packages
import numpy as np
import pandas as pd
import time, warnings
import datetime as dt
warnings.filterwarnings("ignore")
# Get the Data
# Read the data
df=pd.read_csv("retail_data.csv")
df.head()
# RFM Analysis
** RFM ** (Recency, Frequency, Monetary) analysis first we need to create three features R , F & M from the data
lets create those features
## Recency
# To calculate recency, we need to find out **when was the customer's most recent purchase.**.
# Create a new column called date which contains the date of invoice only
df['date'] = pd.DatetimeIndex(df['InvoiceDate']).date
# Group by customers and check last date of purchase
recency_df = df.groupby(by='CustomerID', as_index=False)['date'].max()
recency_df.columns = ['CustomerID','LastPurshaceDate']
# Calculate recent date to find recency wrt to this date
recent_date=recency_df.LastPurshaceDate.max()
print(recent_date)
# Calculate recency
recency_df['Recency'] = recency_df['LastPurshaceDate'].apply(lambda x: (recent_date - x).days)
recency_df.head()

Now in the same way we will calculate both the frequency and the monetary values.
# ## Frequency
# To calculate Frequency we need to check **How often a customer makes a purchase**.
# Drop duplicates
df1= df
df1.drop_duplicates(subset=['InvoiceNo', 'CustomerID'], keep="first", inplace=True)
# Calculate the frequency of purchases
frequency_df = df1.groupby(by=['CustomerID'], as_index=False)['InvoiceNo'].count()
frequency_df.columns = ['CustomerID','Frequency']
frequency_df.head()
# ## Monetary
# To calculate Monetary value **How much money did the customer spent during the timeframe?**
# Create column total cost
df['TotalCost'] = df['Quantity'] * df['UnitPrice']
monetary_df = df.groupby(by='CustomerID',as_index=False).agg({'TotalCost': 'sum'})
monetary_df.columns = ['CustomerID','Monetary']
monetary_df.head()
# ## Create RFM Table
# Merge recency dataframe with frequency dataframe
temp_df = recency_df.merge(frequency_df,on='CustomerID')
temp_df.head()
# Merge with monetary dataframe to get a table with the 3 columns
rfm_df = temp_df.merge(monetary_df,on='CustomerID')
# Use CustomerID as index
rfm_df.set_index('CustomerID',inplace=True)
# Check the head
rfm_df.head()

# Rank each metric R , F & M rfm_df['R_rank'] = rfm_df['Recency'].rank( ascending=False) rfm_df['F_rank'] = rfm_df['Frequency'].rank(ascending=True) rfm_df['M_rank'] = rfm_df['Monetary'].rank(ascending=True) rfm_df.head() # normalize each rank with Max rank rfm_df['R_rank_norm']=(rfm_df['R_rank']/rfm_df['R_rank'].max())*100 rfm_df['F_rank_norm']=(rfm_df['F_rank']/rfm_df['F_rank'].max())*100 rfm_df['M_rank_norm']=(rfm_df['F_rank']/rfm_df['M_rank'].max())*100 rfm_df.head() # Now apply our equation and create final score **Consolidated Score = 0.15*R_rank_norm + 0.28*F_rank_norm + 0.57M_rank_norm** rfm_df['RFM_Score']=0.15*rfm_df['R_rank_norm']+0.28*rfm_df['F_rank_norm']+0.57*rfm_df['M_rank_norm'] rfm_df=rfm_df.round(0) rfm_df.head()

# ## Customer segments with RFM Model # # Segment customers based on RFM score # 0 - 50 - Low valued customer # 50 - 75 - Medium valued customer # 76 - 100 - High valued customer rfm_df["Customer_segment"]=np.where(rfm_df['RFM_Score'] > 75 ,"High Value Customer",(np.where(rfm_df['RFM_Score'] < 50 , "Low value Customer" ,"Medium Value Customer"))) rfm_df.head()

Now that we know our customer segments, we can choose how to orient ourselves or deal with each segment.
For instance:
High value customer: They are your loyal customers, so please give them constant support through customer service.
Mid-value customer: Send them personalized sales emails and encourage them to buy more
Low value customer: These customers are about to leave or enter an inactive stage, apply reactivation strategies for them.
In Python and R we have several packages that support RFM analysis and there are also several ways to derive an RFM score.
Hope you like this article. Happy learning 🙂
The media shown in this article is not the property of DataPeaker and is used at the author's discretion.



