<jupyter_start><jupyter_text>Performing Customer AnalyticsIn this lesson, we will be programmatically performing customer analytics on the transactional dataset that we've cleaned in the previous lesson.Our goal with this lesson is to learn how to implement the knowledge we've gained till now in order to find answers to meaningful customer-related questions. Let us start by importing the necessary libraries,<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline<jupyter_output><empty_output><jupyter_text>Next, importing the CSV file called `customer_dataset.csv` which contains information about the purchases made by the customers.<jupyter_code># Read the CSV data as a Pandas DataFrame
customer_df = pd.read_csv('data/customer_dataset.csv')
# Looking at the first five rows
customer_df.head()<jupyter_output><empty_output><jupyter_text>Let us also view the shape of the DataFrame to determine how many rows of data are in the cleaned dataset.<jupyter_code># Printing the shape of the DataFrame
customer_df.shape<jupyter_output><empty_output><jupyter_text>We can start our analysis by determining how many unique data values are present in each column of the DataFrame. We will be using the `nunique()` method off of the Pandas DataFrame for this.<jupyter_code># Printing the number of unique data values present in each column
customer_df.nunique()<jupyter_output><empty_output><jupyter_text>The dataset holds information about 4372 unique customers from 37 different countries.Also, we can clearly see that even though there are 400,000+ recorded transactions, there are only 22,189 unique invoice numbers. Therefore, we can conclude that the invoice number is not unique to each transaction.Now, let us find the total number of unique customers per country. We can use the `groupby()` method off of the Pandas DataFrame for this.<jupyter_code># Getting the total number of unique customers per country
customer_df.groupby(['Country'])[['CustomerID']].nunique()<jupyter_output><empty_output><jupyter_text>Let us assign this DataFrame to a variable, rename the column and sort it based on the number of unique customers per country.<jupyter_code># Getting the total number of unique customers per country
df_country = customer_df.groupby(['Country'])[['CustomerID']].nunique()

# Renaming the column names
df_country.columns = ['no_of_customers']

# Sorting the DataFrame based on the number of customers
df_country = df_country.sort_values('no_of_customers', ascending=False)

# Looking at the first five rows
df_country.head()<jupyter_output><empty_output><jupyter_text>Now that we have our sorted DataFrame, let us visualize it using a bar plot.<jupyter_code># Plotting a bar plot
df_country.plot(kind='bar', figsize = (18,6))<jupyter_output><empty_output><jupyter_text>We can clearly see how the customers are distributed per country using the bar plot.As a next step, let us generate insights using the four methods of analytics we have learnt before:- Using **Descriptive Analytics**, we can describe the plot stating that most of the customers of the online retail store are from the United Kingdom. Also, we can also conclude that most of the customers of the online retail store are based in Europe in comparison to other continents.- Using **Diagnostic Analytics**, we can diagnose that the cause for the large number of customers coming in from Europe is because the online retail store must have heavily marketed itself in Europe rather than the other continents.- Using **Predictive Analytics**, we can predict that the online retail store will continue getting more customers from the United Kingdom since there is already a massive number of customer base in the United Kingdom.- Using **Prescriptive Analytics**, we can prescribe the online retail store to further invest in marketing in the United Kingdom since number of conversions are very good over there. Now, let us move on to understand how the customers are generating revenue for the online retail store. For this, we will be calculating the total amount of transaction per month. So, let us extract the year and month information from the `InvoiceDate` column.<jupyter_code># Looking at the first five rows
customer_df.head()
# Getting only the year and month from the date column
pd.to_datetime(customer_df['InvoiceDate']).apply(lambda x:x.strftime("%Y-%m"))
# Assigning the extracted values to a new column 
customer_df['InvoiceYearMonth'] = pd.to_datetime(customer_df['InvoiceDate']).apply(lambda x:x.strftime("%Y-%m"))
# Looking at the first five rows
customer_df.head()<jupyter_output><empty_output><jupyter_text>We can now calculate the total revenue amount for each month per year by using the `groupby()` method as before and finding the sum of the column instead of the unique number of data elements.<jupyter_code># Getting the total revenue per month per year
df_revenue = customer_df.groupby(['InvoiceYearMonth'])[['AmountSpent']].sum()

# Looking at the first five rows
df_revenue.head()<jupyter_output><empty_output><jupyter_text>Next, let us plot the values to see the trend of amount spent by the customers for each month.<jupyter_code># Plotting a line plot
df_revenue.plot(kind='line', figsize = (18,6))<jupyter_output><empty_output><jupyter_text>We can see straightaway that the sale has dropped significantly in the December of 2011. Is the online retail store losing customers?Let us find out the reason for this. We can find the date and time at which the last data point was collected in this DataFrame by finding the maximum value of the `InvoiceDate` column.<jupyter_code># Finding the maximum value of the DateTime column
customer_df['InvoiceDate'].max()<jupyter_output><empty_output><jupyter_text>So, the early stopping of the data collection was the cause for the downward fall of sales in December. Let us now shift our focus a little bit more towards the customers and find how many monthly active customers were present in each month.<jupyter_code># Creating monthly active customers DataFrame by counting unique Customer IDs
df_monthly_active = customer_df.groupby('InvoiceYearMonth')[['CustomerID']].nunique()

# Renaming the column name
df_monthly_active.columns = ['no_of_unique_customers']

# Looking at the first five rows
df_monthly_active.head()<jupyter_output><empty_output><jupyter_text>Now, plotting the data using a bar plot.<jupyter_code># Plotting a bar plot
df_monthly_active.plot(kind='bar', figsize = (18,6))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.06552838024919243, 'fraction_numerical': 0.0046146746654360865, 'mean_word_length': 6.1607929515418505, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '413121', 'license': 'MIT', 'n_tokens_mistral': 1747, 'n_tokens_neox': 1687, 'n_words': 808, 'path': '2. Performing Customer Analytics/Performing Customer Analytics.ipynb', 'repo_name': 'theclickreader/customer-analytics-for-businesses', 'size': '6501'}