The Wayback Machine - https://web.archive.org/web/20240601183132/https://www.geeksforgeeks.org/active-product-sales-analysis-using-matplotlib-in-python/
Open In App

Active Product Sales Analysis using Matplotlib in Python

Last Updated : 07 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Every modern company that engages in online sales or maintains a specialized e-commerce website now aims to maximize its throughput in order to determine what precisely their clients need in order to increase their chances of sales. The huge datasets handed to us can be properly analyzed to find out what time of day has the highest user activity in terms of transactions.

In this post, We will use Python Pandas and Matplotlib to analyze the insight of the dataset. We can use the column Transaction Date, in this case, to glean useful insights on the busiest time (hour) of the day. You can access the entire dataset here.

Stepwise Implementation

Step 1:

First, We need to create a Dataframe of the dataset, and even before that certain libraries have to be imported.

Python3




import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
  
Order_Details = pd.read_csv('Order_details(masked).csv')


Output:

 

Step 2:

Create a new column called Time that has the DateTime format after converting the Transaction Date column into it. The DateTime format, which has the pattern YYYY-MM-DD HH:MM:SS, can be customized however you choose. Here we’re more interested in obtaining hours, so we can have an Hour column by using an in-built function for the same:

Python3




# here we have taken Transaction
# date column
Order_Details['Time'] = pd.to_datetime(Order_Details['Transaction Date'])
  
# After that we extracted hour 
# from Transaction date column
Order_Details['Hour'] = (Order_Details['Time']).dt.hour


Step 3: 

We then require the “n” busiest hours. For that, we get the first “n” entries in a list containing the occurrence rates of the hours when the transaction took place. To further simplify the manipulation of the provided data in Python, we may utilize value counts for frequencies and tolist() to convert to list format. We are also compiling a list of the associated index values.

Python3




# n =24 in this case, can be modified
# as per need to see top 'n' busiest hours
timemost1 = Order_Details['Hour'].value_counts().index.tolist()[:24] 
  
timemost2 = Order_Details['Hour'].value_counts().values.tolist()[:24]


Step 4:

Finally, we stack the indices (hour) and frequencies together to yield the final result.

Python3




tmost = np.column_stack((timemost1,timemost2))
  
print(" Hour Of Day" + "\t" + "Cumulative Number of Purchases \n")
print('\n'.join('\t\t'.join(map(str, row)) for row in tmost))


 

Step 5: 

Before we can create an appropriate data visualization, we must make the list slightly more customizable. To do so, we gather the hourly frequencies and perform the following tasks:

Python3




timemost = Order_Details['Hour'].value_counts()
timemost1 = []
  
for i in range(0,23):
    timemost1.append(i)
      
timemost2 = timemost.sort_index()
timemost2.tolist()
timemost2 = pd.DataFrame(timemost2)


Step 6: 

For data visualization, we will proceed with Matplotlib for better comprehensibility, as it is one of the most convenient and commonly used libraries. But, It is up to you to choose any of the pre-existing libraries like Matplotlib, Ggplot, Seaborn, etc., to plot the data graphically.

The commands written below are mainly to ensure that X-axis takes up the values of hours and Y-axis takes up the importance of the number of transactions affected, and also various other aspects of a line chart, including color, font, etc., to name a few.

Python3




plt.figure(figsize=(20, 10))
  
plt.title('Sales Happening Per Hour (Spread Throughout The Week)',
          fontdict={'fontname': 'monospace', 'fontsize': 30}, y=1.05)
  
plt.ylabel("Number Of Purchases Made", fontsize=18, labelpad=20)
plt.xlabel("Hour", fontsize=18, labelpad=20)
plt.plot(timemost1, timemost2, color='m')
plt.grid()
plt.show()


Product Sales Analysis Using Python

 

The results are indicative of how sales typically peak in late evening hours prominently, and this data can be incorporated into business decisions to promote a product during that time specifically.



Similar Reads

RFM Analysis Analysis Using Python
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly. What is RFM analysis? RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium
3 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Amazon Product Reviews Sentiment Analysis in Python
Amazon gives a platform to small businesses and companies with modest resources to grow larger. And Because of its popularity, people actually spend time and write detailed reviews, about the brand and the product. So, by analyzing that data we can tell companies a lot about their products and also the ways to enhance the quality of the product. Bu
4 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Analysis of test data using K-Means Clustering in Python
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-lib Let's first visualize test data with Multiple Features using matplot-lib tool. # importing required tools import numpy as np from matplotlib import pyplot as plt # creating two test data X = np.ra
2 min read
Olympics Data Analysis Using Python
In this article, we are going to see the Olympics analysis using Python. The modern Olympic Games or Olympics are leading international sports events featuring summer and winter sports competitions in which thousands of athletes from around the world participate in a variety of competitions. The Olympic Games are considered the world's foremost spo
4 min read
Flipkart Reviews Sentiment Analysis using Python
This article is based on the analysis of the reviews and ratings user gives on Flipkart to make others aware of their experience and moreover about the quality of the product and brand. So, by analyzing that data we can tell the users a lot about the products and also the ways to enhance the quality of the product. Today we will be using Machine Le
5 min read
YouTube Data Scraping, Preprocessing and Analysis using Python
YouTube is one of the oldest and most popular video distribution platforms in the world. We can't even imagine the video content available here. It has billion of users and viewers, which keeps on increasing every passing minute. Since its origins, YouTube and its content have transformed very much. Now we have SHORTS, likes, and many more features
5 min read
Zomato Data Analysis Using Python
Python and its following libraries are used to analyze Zomato data. Numpy- With Numpy arrays, complex computations are executed quickly, and large calculations are handled efficiently.Matplotlib- It has a wide range of features for creating high-quality plots, charts, histograms, scatter plots, and more.Pandas- The library simplifies the loading of
4 min read
8 Types of Plots for Time Series Analysis using Python
Time series data Time series data is a collection of observations chronologically arranged at regular time intervals. Each observation corresponds to a specific time point, and the data can be recorded at various frequencies (e.g., daily, monthly, yearly). This type of data is very essential in many fields, including finance, economics, climate sci
10 min read
Article Tags :
Practice Tags :