<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Munaz Anjum on Medium]]></title>
        <description><![CDATA[Stories by Munaz Anjum on Medium]]></description>
        <link>https://medium.com/@munaz-anjum?source=rss-72567783a912------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mVB3vKOxWPDD-BVx</url>
            <title>Stories by Munaz Anjum on Medium</title>
            <link>https://medium.com/@munaz-anjum?source=rss-72567783a912------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:21:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@munaz-anjum/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SMART Insights for E-Commerce: Calculated Metrics in GA4 and Pareto Principle with BigQuery and…]]></title>
            <link>https://munaz-anjum.medium.com/smart-insights-for-e-commerce-calculated-metrics-in-ga4-and-pareto-principle-with-bigquery-and-bba2d07b5d66?source=rss-72567783a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba2d07b5d66</guid>
            <category><![CDATA[ga4]]></category>
            <category><![CDATA[calculated-metrics]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pareto-principle]]></category>
            <dc:creator><![CDATA[Munaz Anjum]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 15:33:46 GMT</pubDate>
            <atom:updated>2023-11-04T18:00:10.808Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>SMART Insights for E-Commerce: Calculated Metrics in GA4 and Pareto Principle with BigQuery and Python!</strong></h3><p>I’m writing this post that can help you leverage BigQuery to pull calculated metrics for eCommerce in GA4. Additionally, I’ll delve into the Pareto Principle or the 80/20 rule, which posits that a majority of revenue (80%) is typically generated from a minority (20%) of products.</p><p><strong>Part I:</strong> A Quick Guide to Pulling Custom Calculated Metrics Using BigQuery</p><p><strong>Part II:</strong> Using BigQuery and Python to Investigate the Pareto Principle in E-Commerce Data</p><p>It’s important to note, though, that the Pareto Principle should be deemed more as a useful framework rather than an absolute rule. It’s unlikely that every dataset will conform precisely to an 80/20 split. The essential lesson is recognizing that often a small fraction of causes can produce a large portion of the effects. This insight is important for creating more effective business strategies and optimizing resource distribution.</p><p>All through my experience, I have noticed that Google Analytics is prone to error, and you can’t avoid it due to various reasons — both internal and external. That’s why relying on simple averages and calculated metrics for your default data in report is not advisable. Further, GA4 default report has a very limited scope for data manipulation if we wish to perform.</p><p>The only trusted guide is bigQuery — your raw data. You can remove duplicate, filter null values, or eliminate any outlier. Data cleansing is the foundation of generating true insights. Further, the default calculated metric is just basic calculation you can create with limitation up to 5 calc metrics you could set up for your standard property.</p><p><strong>Prerequisites:</strong></p><p>· Set up bigQuery and access to bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131.</p><p>· Python — importing Panda and Matplotlib in your Jupyter Notebook/Colab</p><p><strong>PART I:</strong></p><p>Let’s dive in.</p><p>The most important question to start with — <strong>is my data reliable?</strong> To validate your assumption, you need to first check the quality of data.</p><p>Let’s say, for example, I want to understand sales, cart to add, orders and quantity sold for items during a given month [<strong>January 1, 2021 — March 31, 2021</strong>].</p><p>Here is the query.</p><pre>-- Declare the analysis date<br>DECLARE date1 STRING;<br>DECLARE date2 STRING;<br><br>SET date1 = &#39;20210101&#39;;<br>SET date2 = &#39;20210331&#39;;<br><br>-- Sales data<br>WITH sales_data AS (<br>  SELECT<br>    items.item_id,<br>    COUNT(*) as orders,<br>    SUM(items.quantity) as total_quantity_ordered,<br>    SUM(items.item_revenue) as item_revenue<br>  FROM<br>    `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>    UNNEST(items) as items<br>  WHERE<br>    _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;purchase&#39;<br>  GROUP BY items.item_id<br>),<br><br>-- Add to carts data<br>add_to_carts_data AS (<br>  SELECT<br>    items.item_id,<br>    items.item_name,<br>    COUNT(*) as add_to_carts<br>  FROM<br>    `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>    UNNEST(items) as items<br>  WHERE<br>    _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;add_to_cart&#39;<br>  GROUP BY items.item_id, items.item_name<br>)<br><br>-- Final SELECT joining sales data with add to carts data<br>SELECT<br>  c.item_id,<br>  c.item_name,<br>  c.add_to_carts,<br>  s.orders,<br>  s.total_quantity_ordered<br>FROM add_to_carts_data c<br>LEFT JOIN sales_data s ON c.item_id = s.item_id<br>ORDER BY s.orders DESC<br><br><br>-- CTE for sales data excluding items with &quot;(not set)&quot; in item_id or item_name<br>WITH sales AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    SUM(items.quantity) AS item_quantity,<br>    COUNT(DISTINCT event_timestamp) AS orders,<br>    SUM(items.item_revenue) AS item_revenue<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;purchase&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id<br>),<br><br>-- CTE for add-to-carts data excluding items with &quot;(not set)&quot; in item_id or item_name<br>add_to_carts AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    items.item_name AS item_name,<br>    COUNT(DISTINCT event_timestamp) AS add_to_carts<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;add_to_cart&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id, item_name<br>)<br><br>-- Final SELECT to combine sales and add_to_carts data<br>SELECT<br>  c.item_id AS item_id,<br>  c.item_name AS item_name,<br>  c.add_to_carts AS add_to_carts,<br>  IFNULL(s.orders, 0) AS orders,<br>  IFNULL(s.item_quantity, 0) AS total_quantity_ordered<br>FROM add_to_carts AS c<br>LEFT JOIN sales AS s ON c.item_id = s.item_id<br>ORDER BY orders DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*H0qlVvQ92AgvScNmMfjhMQ.png" /></figure><p>This output is expected since we are using obfuscated data of bigQuery for GA4, however, you need to check your own dataset if columns and rows make any sense. As shown in the above screenshot, the column, and the corresponding values in 1 row is (not set) with apparently an outlier — <strong>orders (300)</strong>.</p><p>Use statistical methods like IQR or boxplot for identifying the outlier. Even a simple histogram can help you find it.</p><p>Investigate the cause and check if it is due to any tracking error or other glitches. Try to eliminate such data that does not make any sense. It tends to skew averages and produce a misleading analysis.</p><p><strong>Data Cleansing:</strong></p><p>In the above example, I would like to cleanse the data first by excluding:</p><p>· Null</p><p>· Not set</p><p>*You may also eliminate duplicates, or any weird records in your table. Here is the revised query.</p><pre>-- Declare the analysis date<br>DECLARE date1 STRING;<br>DECLARE date2 STRING;<br><br>SET date1 = &#39;20210101&#39;;<br>SET date2 = &#39;20210331&#39;;<br><br>-- CTE for sales data excluding items with &quot;(not set)&quot; in item_id or item_name<br>WITH sales AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    SUM(items.quantity) AS total_quantity,<br>    COUNT(DISTINCT CONCAT(CAST(event_timestamp AS STRING), &#39;-&#39;, CAST(event_bundle_sequence_id AS STRING))) AS orders,<br>    SUM(items.item_revenue) AS total_revenue<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;purchase&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id<br>),<br><br>-- CTE for add-to-carts data excluding items with &quot;(not set)&quot; in item_id or item_name<br>add_to_carts AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    items.item_name AS item_name,<br>    COUNT(DISTINCT CONCAT(CAST(event_timestamp AS STRING), &#39;-&#39;, CAST(event_bundle_sequence_id AS STRING))) AS add_to_carts<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;add_to_cart&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id, item_name<br>)<br><br>-- Final SELECT joining sales and add_to_carts data<br>SELECT<br>  a.item_id,<br>  a.item_name,<br>  a.add_to_carts,<br>  s.total_quantity,<br>  s.orders,<br>  s.total_revenue<br>FROM add_to_carts a<br>LEFT JOIN sales s ON a.item_id = s.item_id<br>ORDER BY s.orders DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*jqLIKJbUqOSUHPHz26O-AA.png" /></figure><p>The data in the table is clean now. Let us proceed now to adding calculated metrics.</p><p><strong>Calculated Metrics:</strong></p><p>Now let’s add some calculated metrics:</p><p>1. <strong>Average Price</strong> = Total Revenue / Total Quantity Sold</p><p>2. <strong>Average Quantity Per Order</strong> = Average Quantity Per Order = Total Quantity Sold / Number of Orders</p><p>3. <strong>Cart Conversion Rate</strong> = (Number of Orders / Add to Carts) * 100</p><p>4. <strong>Cart Abandonment Rate</strong> = (Add to Carts — Number of Orders) / Add to Carts) * 100</p><p>The following query will add columns and do the calculations for the desired output.</p><pre>DECLARE date1, date2 STRING;<br>SET (date1, date2) = (&#39;20210101&#39;,&#39;20210331&#39;);<br><br>-- CTE for sales data excluding items with &quot;(not set)&quot; in item_id or item_name<br>WITH sales AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    SUM(items.quantity) AS total_quantity,<br>    COUNT(DISTINCT event_timestamp) AS orders,<br>    SUM(items.item_revenue) AS total_revenue<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;purchase&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id<br>),<br><br>-- CTE for add-to-carts data excluding items with &quot;(not set)&quot; in item_id or item_name<br>add_to_carts AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    items.item_name AS item_name,<br>    COUNT(DISTINCT event_timestamp) AS add_to_carts<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;add_to_cart&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id, item_name<br>)<br><br>-- Final SELECT to combine sales and add-to-carts data<br>SELECT<br>  c.item_id AS item_id,<br>  c.item_name AS item_name,<br>  c.add_to_carts AS add_to_carts,<br>  IFNULL(s.orders, 0) AS orders,<br>  IFNULL(s.total_quantity, 0) AS total_quantity_ordered,<br>  IFNULL(s.total_revenue, 0.0) AS revenue,<br>  -- Calculate average price (revenue divided by quantity)<br>  IFNULL(s.total_revenue / NULLIF(s.total_quantity, 0), 0.0) AS avg_price,<br>  -- Calculate average quantity per order<br>  IFNULL(s.total_quantity / NULLIF(s.orders, 0), 0.0) AS avg_quantity_per_order,<br>  -- Calculate cart conversion rate (orders divided by add to carts)<br>  IFNULL(s.orders / NULLIF(c.add_to_carts, 0), 0.0) AS cart_conversion_rate,<br>  -- Calculate cart abandonment rate ensuring it is not negative<br>  GREATEST(1 - IFNULL(s.orders / NULLIF(c.add_to_carts, 0), 0.0), 0) AS cart_abandonment_rate<br>FROM add_to_carts AS c<br>LEFT JOIN sales AS s ON c.item_id = s.item_id<br>ORDER BY orders DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*tJWXGULH-PNcGB0Tcd6c_Q.png" /></figure><p><a href="https://emojipedia.org/warning">⚠️</a><strong> Caution: </strong>Complex queries can escalate costs; monitor data usage, like the <strong>66.66 MB </strong>processed as shown in the image below. So, keep track of bytes to manage bigQuery expenses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*i6va54lGPXW3PjQCVUqnYA.png" /></figure><p>The best recommendation could be to download the data in excel, if possible and do the formula-based calculations, or use Python/R. This may help you save the additional costs.</p><p><strong>Data Analysis Preparation:</strong></p><p>The next step is to export the table for data analysis. You have many options to explore it with –</p><p>1) Google Sheets</p><p>2) Google Python Notebook</p><p>3) Looker Studio</p><p>Alternatively, you can save file in CSV, Google Drive, JSON Local File, and Google Sheets, however, you need to check the size of the file. There is a limitation of saving them in different formats. Since the size of the file here is 66.66 MB for the above query, I will use Google Colab.</p><p><strong>Explore with Colab:</strong></p><p>Upon exploring the above query with Colab, you’d get prompted with the following set up:</p><pre># @title Setup<br>from google.colab import auth<br>from google.cloud import bigquery<br>from google.colab import data_table<br><br>project = &#39;lustrous-acumen-399315&#39; # Project ID inserted based on the query results selected to explore<br>location = &#39;US&#39; # Location inserted based on the query results selected to explore<br>client = bigquery.Client(project=project, location=location)<br>data_table.enable_dataframe_formatter()<br>auth.authenticate_user()</pre><p><strong>Result set loaded from bigQuery job as a DataFrame:</strong></p><pre># Running this code will read results from your previous job<br><br>job = client.get_job(&#39;script_job_d956955c0ac16c7173edb7d068bd0f9c_0&#39;) # Job ID inserted based on the query results selected to explore<br>results = job.to_dataframe()<br>results</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*BcZDYJp4uSrUbK9UTtD4kw.png" /></figure><p><strong>Import Necessary Libraries:</strong></p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Histograms for distribution<br>results.hist(bins=30, figsize=(14,10))<br>plt.tight_layout()<br>plt.show()<br><br># Boxplots to check for outliers<br>plt.figure(figsize=(14, 8))<br>results.boxplot()<br>plt.xticks(rotation=45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Y00nqRqfTFDfehSejY-qEw.png" /></figure><p>There is a pattern of right-skewness across all the variables except <em>cart_abandonment_rate,</em> which indicates that high values are less frequent in the dataset.</p><p>A high number of items have a cart conversion rate of 0 and a cart abandonment rate of 1, suggesting that there may be many instances where customers add items to the cart but do not follow through with a purchase. This is subject to further investigation.</p><p>The presence of such skewed distributions and the disparity in cart conversion and abandonment rates suggest that there might be room for improving the sales funnel to convert cart additions into actual sales.</p><p>The high cart abandonment rate across the board could indicate issues in the checkout process or customer hesitation, which could be areas for potential improvement.</p><p>In short, there are a few superstar items that are really popular generating major chunk of revenue. The top products shown in the table validate the fact as can be seen above.</p><p><strong>What are the products that have zero abandonment rate?</strong></p><p>Let’s try to find out. Use the below code:</p><pre>results[&#39;purchase_rate&#39;] = results[&#39;orders&#39;] / results[&#39;add_to_carts&#39;]<br><br># Now we filter for items that were added to carts at least once<br># and have a purchase rate of 1 (purchased every time they were added to a cart)<br>always_purchased_products = results[(results[&#39;add_to_carts&#39;] &gt; 0) &amp; (results[&#39;purchase_rate&#39;] == 1)]<br><br># Seeing the results sorted by the most added to cart<br>sorted_always_purchased_products = always_purchased_products.sort_values(by=&#39;add_to_carts&#39;, ascending=False)<br><br># Selecting only the relevant columns for clarity<br>final_list_always_purchased = sorted_always_purchased_products[[&#39;item_id&#39;, &#39;item_name&#39;, &#39;add_to_carts&#39;, &#39;orders&#39;, &#39;purchase_rate&#39;]]<br><br># Display the final list of always purchased products<br>print(final_list_always_purchased)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*wd38hYIp5JmFxR-wNnmztg.png" /></figure><p><strong>What are the products that have 100% cart abandonment rate?</strong></p><p>Here is the query:</p><pre># We add a new column to determine the purchase rate<br>results[&#39;purchase_rate&#39;] = results[&#39;orders&#39;] / results[&#39;add_to_carts&#39;]<br><br># Now we filter for items that were added to carts at least once<br># but have a purchase rate of 0 (never purchased)<br>never_purchased_products = results[(results[&#39;add_to_carts&#39;] &gt; 0) &amp; (results[&#39;orders&#39;] == 0)]<br><br># Seeing the results sorted by the most added to cart<br>sorted_never_purchased_products = never_purchased_products.sort_values(by=&#39;add_to_carts&#39;, ascending=False)<br><br># Selecting only the relevant columns for clarity<br>final_list = sorted_never_purchased_products[[&#39;item_id&#39;, &#39;item_name&#39;, &#39;add_to_carts&#39;, &#39;orders&#39;, &#39;purchase_rate&#39;]]<br><br># Display the final list<br>print(final_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*85s2nzVxKGFsYJ6jA5eS6g.png" /></figure><p><strong>PART II:</strong></p><p>Alright.</p><p>Can we say that products that have 0% cart abandonment rate are driving most revenue? I’d rather be interested in knowing — <strong>what are my top 20% of products that drive maximum revenue — say (80%).</strong></p><p>Let’s test this out using the Pareto Principle.</p><p><strong>The Pareto Principle:</strong></p><p>Apply the Pareto principle (80/20 rule) to your sales data to identify the top 20% of products that might be generating 80% of the revenue. In order to test the Pareto Principle, we need to:</p><p>1. Calculate the total revenue.</p><p>2. Calculate the cumulative revenue of products in descending order.</p><p>3. Identify the point where the cumulative revenue reaches 80% of the total revenue.</p><p>Here is an extended version of the query that incorporates these steps:</p><pre>-- First, declare the variables for your date range<br>DECLARE date1, date2 STRING;<br>SET (date1, date2) = (&#39;20210101&#39;, &#39;20210331&#39;);<br><br>-- CTE for sales data excluding items with &quot;(not set)&quot; in item_id or item_name<br>WITH sales AS (<br>  SELECT<br>    items.item_id AS item_id,<br>    items.item_name AS item_name,<br>    SUM(items.quantity) AS item_quantity,<br>    COUNT(DISTINCT event_timestamp) AS orders,<br>    SUM(items.item_revenue) AS item_revenue<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>  UNNEST(items) AS items<br>  WHERE _TABLE_SUFFIX BETWEEN date1 AND date2<br>    AND event_name = &#39;purchase&#39;<br>    AND items.item_id IS NOT NULL<br>    AND items.item_name IS NOT NULL<br>    AND items.item_id != &#39;(not set)&#39;<br>    AND items.item_name != &#39;(not set)&#39;<br>  GROUP BY item_id, item_name<br>),<br><br>-- CTE to calculate total revenue<br>total_revenue_cte AS (<br>  SELECT SUM(item_revenue) AS total_revenue<br>  FROM sales<br>),<br><br>-- CTE to calculate cumulative revenue<br>cumulative_revenue AS (<br>  SELECT<br>    item_id,<br>    item_name,<br>    item_revenue,<br>    SUM(item_revenue) OVER (ORDER BY item_revenue DESC) AS cumulative_revenue,<br>    (SUM(item_revenue) OVER (ORDER BY item_revenue DESC) / (SELECT total_revenue FROM total_revenue_cte)) * 100 AS cumulative_percent<br>  FROM sales<br>)<br><br>-- Selecting the top 20% of items by revenue including product names<br>SELECT *<br>FROM cumulative_revenue<br>WHERE cumulative_percent &lt;= 80<br>ORDER BY item_revenue DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*LeXMIzMnf1ruYPBUTWIFzw.png" /></figure><p><strong>Next steps:</strong></p><p>Explore it with Colab and load you’d see the loaded from bigQuery job as DataFrame.</p><p>Use the following Python code:</p><pre># Display the first few rows of the DataFrame<br>print(results.head())<br><br># Check data types of each column<br>print(results.dtypes)</pre><p>Here is the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*oFhlXhnJDF9g1waVc8sH2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*nvBQ876l4tA872AqFqKVBA.png" /></figure><p>Plotting it in the graph:</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br><br># Assuming you have already imported your dataset into a DataFrame called &#39;results&#39;<br># Make sure &#39;results&#39; contains the relevant columns like &#39;item_name&#39; and &#39;item_revenue&#39;<br><br># Sort the DataFrame by item_revenue in descending order<br>results_sorted = results.sort_values(by=&#39;item_revenue&#39;, ascending=False)<br><br># Calculate the cumulative percentage of revenue<br>results_sorted[&#39;cumulative_percent&#39;] = (<br>    results_sorted[&#39;item_revenue&#39;].cumsum() / results_sorted[&#39;item_revenue&#39;].sum() * 100<br>)<br><br># Create a Pareto chart with both bars and a line<br>fig, ax1 = plt.subplots(figsize=(12, 6))<br><br># Plot the bars<br>bars = ax1.bar(results_sorted[&#39;item_name&#39;], results_sorted[&#39;item_revenue&#39;], color=&#39;blue&#39;, alpha=0.7)<br><br># Make the y-axis label, ticks, and tick labels match the line color.<br>ax1.set_xlabel(&#39;Items&#39;)<br>ax1.set_ylabel(&#39;Revenue&#39;, color=&#39;b&#39;)<br>ax1.tick_params(&#39;y&#39;, colors=&#39;b&#39;)<br><br># Turn the grid on for the y-axis<br>ax1.grid(True)<br><br># Plot the cumulative percentage line<br>ax2 = ax1.twinx()<br>line = ax2.plot(results_sorted[&#39;item_name&#39;], results_sorted[&#39;cumulative_percent&#39;], color=&#39;red&#39;, marker=&#39;o&#39;, label=&#39;Cumulative Percentage&#39;)<br><br># Make the y-axis label, ticks, and tick labels match the line color.<br>ax2.set_ylabel(&#39;Cumulative Percentage (%)&#39;, color=&#39;r&#39;)<br>ax2.tick_params(&#39;y&#39;, colors=&#39;r&#39;)<br><br># Set the y-axis limit to 0-100 for percentage<br>ax2.set_ylim(0, 100)<br><br># Add a legend<br>lines, labels = ax1.get_legend_handles_labels()<br>lines2, labels2 = ax2.get_legend_handles_labels()<br>ax2.legend(lines + lines2, labels + labels2, loc=&#39;best&#39;)<br><br># Set the title of the plot<br>plt.title(&#39;Pareto Chart - Items by Revenue&#39;)<br><br>plt.tight_layout()  # Adjust layout to make room for the rotated x-axis labels<br><br># Show the Pareto chart<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*5fIRMtJUubO1dnwMm2Qnfw.png" /></figure><p><strong>Analysis:</strong></p><p>Given the total revenue is $5760.00, 80% of this is $4608.00. We need to find out at which item the cumulative revenue exceeds $4608.00 to identify the top-performing items as per the Pareto Principle.</p><p>· After the first item (Google Crewneck Sweatshirt Green), the cumulative revenue is $1276.00.</p><p>· After the second item (Gift Card- $100.00), the cumulative revenue is $2476.00.</p><p>· After the third item (Google Campus Bike), the cumulative revenue is $3604.00.</p><p>· After the fourth item (Google Black Cloud Zip Hoodie), the cumulative revenue is $4691.00.</p><p><strong>The cumulative revenue exceeds the 80% threshold of $4608.00</strong> after the fourth item. Therefore, according to the Pareto Principle, the top-performing items that make up approximately 80% of the total revenue are the first four items on the list:</p><p>· Google Crewneck Sweatshirt Green</p><p>· Gift Card- $100.00</p><p>· Google Campus Bike</p><p>· Google Black Cloud Zip Hoodie</p><p>So in this scenario, 4 out of 5 items, which is 80% of the items, make up more than 80% of the total revenue, not aligning with the classical Pareto distribution of 20% of the items making up 80% of the revenue. However, it does show a significant concentration of revenue among these four items.</p><p><strong>What if we consider only TOP three products?</strong></p><pre># Calculate the total revenue of all items<br>total_revenue_all_items = results_sorted[&#39;item_revenue&#39;].sum()<br><br># Calculate the total revenue of the top three items<br>total_revenue_top_three_items = top_20_percent[&#39;item_revenue&#39;].sum()<br><br># Calculate the revenue contribution percentage<br>revenue_contribution_percentage = (total_revenue_top_three_items / total_revenue_all_items) * 100<br><br># Print the results<br>print(f&quot;Total Revenue of Top Three Items: ${total_revenue_top_three_items:.2f}&quot;)<br>print(f&quot;Total Revenue of All Items: ${total_revenue_all_items:.2f}&quot;)<br>print(f&quot;Revenue Contribution Percentage: {revenue_contribution_percentage:.2f}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*4eJOM6Qm9xjX0H3AkeNZnA.png" /></figure><p><strong>Findings:</strong></p><p>The total revenue for the top three items (Google Crewneck Sweatshirt Green, Gift Card- $100.00, and Google Campus Bike) is $3604.00.</p><p>The overall total revenue from all items is $5760.00.</p><p><strong>To determine the percentage contribution of the top three items to the total revenue:</strong></p><p>Revenue Contribution Percentage = (Total Revenue of All Items/Total Revenue of Top Three Items​)*100</p><p>Revenue Contribution Percentage = (3604.00/5760.00)*100 ≈<strong> 62.57%</strong></p><p>This calculation shows that the top three items contribute approximately <strong>62.57%</strong> of the total revenue. This is a significant portion, but it is less than the 80% that would be indicative of a strict adherence to the Pareto Principle (also known as the 80/20 rule). However, it still demonstrates a concentration of revenue among the top-selling items.</p><p>In both cases, <strong>the data does not perfectly fit in 80/20</strong> rule, however, it shows that Google Crewneck Sweatshirt Green, Gift Card- $100.00, Google Campus Bike and Google Black Cloud Zip Hoodie are the top products that drive (<strong>~80%</strong>) of revenue.</p><p><strong>Key Insights:</strong></p><p>From the above analysis, I have identified the three or four products that contribute substantially to revenue. Marketers can use the popularity of the high-performing items to cross-promote items that are less well-known or have lower sales volumes. In our example, when customers show interest in the Google Crewneck Sweatshirt, they could be shown similar or complementary products.</p><p>What more insights can you drive? Share your thoughts. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba2d07b5d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing BigQuery to Understand Users’ Behavior, Reduce Cart Abandoners and Create SMART…]]></title>
            <link>https://munaz-anjum.medium.com/harnessing-bigquery-to-understand-users-behavior-reduce-cart-abandoners-and-create-smart-0d545d7f5ded?source=rss-72567783a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d545d7f5ded</guid>
            <category><![CDATA[cart-abandonment-solution]]></category>
            <category><![CDATA[ga4]]></category>
            <category><![CDATA[purchasers]]></category>
            <category><![CDATA[users]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Munaz Anjum]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 17:03:44 GMT</pubDate>
            <atom:updated>2023-11-01T05:48:03.065Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Harnessing BigQuery to Understand Users’ Behaviour, Reduce Cart Abandonment and Create SMART Marketing Strategies</strong></h3><p>In a hyper-competitive ecommerce world, gaining insights into user behaviour — particularly regarding purchasing behaviour and cart abandonment — is essential for businesses looking to enhance their customer experience and boost conversions.</p><p>Here is a guidance on leveraging BigQuery to analyze user behaviour and develop customized marketing tactics. Before diving in, it’s important to ensure that you have access to public sample data of GA4 — <a href="https://console.cloud.google.com/bigquery?p=bigquery-public-data&amp;d=ga4_obfuscated_sample_ecommerce&amp;t=events_20210131&amp;page=table">bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131</a>.</p><p>Let’s delve into now!</p><p><strong>A. User Types Category:</strong></p><p>We have categorized users into three distinct types based on their interactions:</p><p>1. <strong>Window Shoppers</strong>: Users who have neither added items to their cart nor made a purchase. They have viewed the products.</p><p>2. <strong>Cart Abandoners</strong>: Users who have added items to their cart but have not made a purchase.</p><p>3. <strong>Purchasers</strong>: Users who have successfully made a purchase.</p><p><strong>B. Querying the Data:</strong></p><p>Below is a sample query that identifies users falling into these categories.</p><pre>WITH PurchaseEvents AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>    AND event_name = &#39;purchase&#39;<br>),<br><br>AddToCartEvents AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>    AND event_name = &#39;add_to_cart&#39;<br>),<br><br>AllUsers AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>)<br><br>SELECT<br>  CASE<br>    WHEN pu.user_pseudo_id IS NOT NULL THEN &#39;Purchasers&#39;<br>    WHEN atc.user_pseudo_id IS NOT NULL AND pu.user_pseudo_id IS NULL THEN &#39;Cart Abandoners&#39;<br>    ELSE &#39;Window Shoppers&#39;<br>  END AS user_type,<br>  COUNT(*) AS user_count<br>FROM AllUsers a<br>LEFT JOIN PurchaseEvents pu ON a.user_pseudo_id = pu.user_pseudo_id<br>LEFT JOIN AddToCartEvents atc ON a.user_pseudo_id = atc.user_pseudo_id<br>GROUP BY user_type;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*da7sJ1RYxCOEignedBjROQ.png" /><figcaption>The query classifies users into different types based on their purchase behaviour and count them.</figcaption></figure><p>Make sure that, when executing the query, the total count of users matches the combined count of the three types of users.</p><p>Here is a sample query:</p><pre>SELECT COUNT(DISTINCT user_pseudo_id) AS total_users_count<br>FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*tSQ0Zr1uY5MsiNTGqKFJjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*NkPnPNOwqxxW-qWFacYCpg.png" /></figure><p><strong>C. Revenue Generated by Purchasers</strong></p><pre>WITH PurchaseEvents AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>    AND event_name = &#39;purchase&#39;<br>),<br><br>AddToCartEvents AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>    AND event_name = &#39;add_to_cart&#39;<br>),<br><br>AllUsers AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>),<br><br>UserRevenue AS (<br>  SELECT<br>    user_pseudo_id,<br>    SUM(ecommerce.purchase_revenue_in_usd) AS total_purchase_revenue_in_usd,<br>    SUM(ecommerce.purchase_revenue) AS total_purchase_revenue<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>  WHERE _TABLE_SUFFIX BETWEEN &#39;20201101&#39; AND &#39;20210131&#39;<br>    AND event_name = &#39;purchase&#39;<br>  GROUP BY user_pseudo_id<br>)<br><br>SELECT<br>  CASE<br>    WHEN pu.user_pseudo_id IS NOT NULL THEN &#39;Purchasers&#39;<br>    WHEN atc.user_pseudo_id IS NOT NULL AND pu.user_pseudo_id IS NULL THEN &#39;Cart Abandoners&#39;<br>    ELSE &#39;Window Shoppers&#39;<br>  END AS user_type,<br>  COUNT(*) AS user_count,<br>  SUM(ur.total_purchase_revenue_in_usd) AS total_purchase_revenue_in_usd,<br>  SUM(ur.total_purchase_revenue) AS total_purchase_revenue<br>FROM AllUsers a<br>LEFT JOIN PurchaseEvents pu ON a.user_pseudo_id = pu.user_pseudo_id<br>LEFT JOIN AddToCartEvents atc ON a.user_pseudo_id = atc.user_pseudo_id<br>LEFT JOIN UserRevenue ur ON a.user_pseudo_id = ur.user_pseudo_id<br>GROUP BY user_type;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*A3-JSM2fzmZ83G-W-STFAg.png" /><figcaption>The query captures three categories of users, and then aggregate their purchase revenue. Window Shoppers and Cart Abandoners have ZERO revenue for obvious reasons. That’s why the purchase_revenue fields show NULL. If you so wish, you can exclude them, and instead query for Purchasers.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*FYeALU6VEo5kUsXyvtZKkw.png" /></figure><p><strong>D. Estimated Loss of Revenue by Window Shoppers</strong></p><p>We can estimate the loss of revenue from products and their prices viewed by window shoppers. Here is an example of query.</p><pre>WITH WindowShoppers AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`<br>  WHERE event_name NOT IN (&#39;add_to_cart&#39;, &#39;purchase&#39;)<br>),<br><br>LossEstimation AS (<br>  SELECT<br>    np.user_pseudo_id,<br>    SUM(CASE WHEN e.event_name = &#39;view_item&#39; THEN item.price ELSE 0 END) AS estimated_loss<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131` AS e<br>  JOIN WindowShoppers AS np ON e.user_pseudo_id = np.user_pseudo_id<br>  LEFT JOIN UNNEST(e.items) AS item -- Properly unnest items within the JOIN<br>  WHERE e.event_name = &#39;view_item&#39;  -- Only consider &#39;view_item&#39; events<br>  GROUP BY np.user_pseudo_id<br>)<br><br>SELECT<br>  le.user_pseudo_id,<br>  le.estimated_loss<br>FROM LossEstimation AS le<br>WHERE le.estimated_loss &gt; 0;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ubZkFM01hFZ1jkGT-gixeg.png" /><figcaption>The query calculates the estimated loss from users who have viewed items (window shopping) but have not proceeded to adding any items to the cart or made a purchase.</figcaption></figure><p><strong>E. Total Estimated Revenue Loss by Window Shoppers</strong></p><pre>WITH WindowShoppers AS (<br>  SELECT DISTINCT user_pseudo_id<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`<br>  WHERE event_name NOT IN (&#39;add_to_cart&#39;, &#39;purchase&#39;)<br>),<br><br>LossEstimation AS (<br>  SELECT<br>    np.user_pseudo_id,<br>    SUM(CASE WHEN e.event_name = &#39;view_item&#39; THEN item.price ELSE 0 END) AS estimated_loss<br>  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131` AS e<br>  JOIN WindowShoppers AS np<br>  ON e.user_pseudo_id = np.user_pseudo_id<br>  LEFT JOIN UNNEST(e.items) AS item<br>  WHERE e.event_name = &#39;view_item&#39;  -- Only consider &#39;view_item&#39; events<br>  GROUP BY np.user_pseudo_id<br>)<br><br>SELECT<br>  SUM(le.estimated_loss) AS total_estimated_loss<br>FROM LossEstimation AS le<br>WHERE le.estimated_loss &gt; 0;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*IYYljs5Y9LBS0xq4kGwr7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*5MQl-qTdXV7U46aSKnojlQ.png" /><figcaption>Note: The revenue figure highlighted in the brown cell represents the estimated lost revenue from Window Shoppers.</figcaption></figure><p>Similarly, we can run a query to pull in data for loss of revenue due to cart abandonment. <strong>Consider this as an assignment for your real data.</strong></p><p>Gaining insights into revenue losses, as illustrated in the provided table, could help businesses to take strategic decisions to optimize their revenue streams. Businesses can reclaim a portion of the lost revenue by optimizing the checkout process, offering timely discounts, or retargeting campaigns.</p><h4><strong>Behavioural Analysis — Products, Traffic, and Purchase Timings</strong></h4><p>In order to understand the behaviour of abandoners and purchasers, we can further add –</p><p>1. What products users have added to cart vs what products they purchased</p><p>2. What sources they have visited through</p><p>3. What time and date users have added products to cart and purchased</p><p>There is a lot we can think of. The sky’s the limit!</p><p>For our simplicity, we are considering the above three.</p><p>Here is the sample query:</p><pre>WITH CartAbandoners AS (<br>    SELECT DISTINCT user_pseudo_id<br>    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`<br>    WHERE event_name IN (&#39;add_to_cart&#39;, &#39;purchase&#39;)<br>),<br><br>CartAbandonerItems AS (<br>    SELECT<br>        TIMESTAMP_SECONDS(CAST(event_timestamp / 1000000 AS INT64)) AS readable_timestamp,  -- Convert to human-readable timestamp<br>        user_pseudo_id,<br>        event_name AS action,<br>        items.item_name AS product_name,<br>        traffic_source.name AS traffic_source_name<br>    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`,<br>    UNNEST(items) AS items<br>    WHERE<br>        event_name IN (&#39;add_to_cart&#39;, &#39;purchase&#39;)<br>        AND user_pseudo_id IN (SELECT user_pseudo_id FROM CartAbandoners)<br>)<br><br>SELECT<br>    readable_timestamp,   <br>    user_pseudo_id,<br>    action,<br>    product_name,<br>    traffic_source_name<br>FROM<br>    CartAbandonerItems;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*94Sl-VgXwrppRM_T7q0Qpg.png" /><figcaption>The query identifies users who have either added items to their cart or made a purchase, then selects detailed actions of these users including source and products.</figcaption></figure><p><strong>Marketing Strategies:</strong></p><p>To create SMART Marketing Strategy, we can use the insights from the bigQuery to tailor our approach:</p><p>S = Specific Goals</p><p>M = Measurable</p><p>A = Actionable</p><p>R = Relevant</p><p>T = Time-sensitive</p><p>Let’s say — we want to identify:</p><p>· Users who have added to cart but have not purchased.</p><p>· Types of devices by cart abandoners</p><p>· The sources of their visit</p><p>Some specific goals here could be — reducing cart abonnement rate, increasing conversion rate, re-engaging abandoned users, or enhancing users’ experience.</p><p>Here is a sample query:</p><pre>WITH CartEvents AS (<br>    SELECT<br>        user_pseudo_id,<br>        MAX(IF(event_name = &#39;add_to_cart&#39;, TRUE, FALSE)) AS added_to_cart,<br>        MAX(IF(event_name = &#39;purchase&#39;, TRUE, FALSE)) AS purchased<br>    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`<br>    GROUP BY user_pseudo_id<br>),<br><br>CartAbandoners AS (<br>    SELECT user_pseudo_id<br>    FROM CartEvents<br>    WHERE added_to_cart = TRUE AND purchased = FALSE<br>),<br><br>-- Retrieve the cart items only for the abandoners<br>CartAbandonerItems AS (<br>    SELECT<br>        TIMESTAMP_SECONDS(CAST(event_timestamp / 1000000 AS INT64)) AS readable_timestamp,<br>        e.user_pseudo_id,<br>        e.event_name AS action,<br>        items.item_name AS product_name,<br>        e.traffic_source.name AS traffic_source_name,<br>        e.device.category AS device_category<br>    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131` AS e<br>    CROSS JOIN UNNEST(e.items) AS items<br>    WHERE<br>        e.event_name = &#39;add_to_cart&#39;<br>        AND e.user_pseudo_id IN (SELECT user_pseudo_id FROM CartAbandoners)<br>)<br><br>-- Final selection of the abandoner cart item events<br>SELECT<br>    readable_timestamp,<br>    user_pseudo_id,<br>    action,<br>    product_name,<br>    traffic_source_name,<br>    device_category<br>FROM<br>    CartAbandonerItems;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*iR6Fr3rLqJ734DGbaH7iZw.png" /><figcaption>The query analyzes the cart-related behaviour of Cart Abandoners and gain insights into their actions, product preferences, and device usage.</figcaption></figure><p>With the device information included, we can refine our marketing strategies such as device-specific retargeting, UX optimization on mobile or desktop, browser compatibility, app vs web, messaging and push notification, etc.</p><p>One noticeable column in the above table is the <strong>readable timestamp.</strong> This “time conversion” is important to understand the exact date and time when an event occurred. For example, we can determine which product was added to the cart and at what specific date and time it occurred.</p><p><strong>Statistical Analysis</strong>: By applying statistical correlation methods, we can, for instance, determine — whether the launch time of a marketing campaign has a statistically significant impact on consumer purchasing behaviour and cart abandonment rate.</p><p>If the <strong>correlation is statistically significant</strong> (p-value &lt; 0.05), we could conclude that launching marketing campaigns at specific time could reduce cart abandonment and increase purchase likelihood.</p><p><strong>Developing Targeted Marketing:</strong></p><p>1. <strong>Ads Retargeting:</strong> We can create retargeting ads specifically for the users who added products to their cart but didn’t make any purchase. We can then device a strategy to personalize the ads with the products they showed interest in.</p><p>2. <strong>Optimize Traffic Sources: </strong>We can analyze <em>traffic_source_name</em> to see where the highest-value users are coming from and adjust marketing budgets to focus on the most effective channels. For example, if organic traffic shows a high rate of cart abandonment, we can optimize our SEO strategy or website usability to improve the shopping experience for organic visitors.</p><p>3. <strong>Personalization: </strong>We can use the <em>product_name</em> data to create dynamic product ads that show the exact items users were interested in. Personalized product recommendations could be beneficial here.</p><p>4. <strong>Urgency and Scarcity</strong>: We can create a sense of urgency with a limited-time offer or discount for the products in the abandoned cart. We can notify users if the stock is low for the items they’ve added to their cart to encourage a quick purchase decision.</p><p>5. <strong>Optimize for Mobile: </strong>If we find many users abandon carts on mobile devices, just to make sure our mobile site, or app is optimized for a seamless checkout process. We might consider additional tool such as Hotjar to understand how users’ interacting with the defined check-out process.</p><p>6. <strong>A/B Testing: </strong>Using A/B testing , we can optimize the checkout process. We can use different versions of our checkout page — <strong>Champion vs Challenger</strong> — to see which one has a lower abandonment rate. We can then measure the statistical significance.</p><p>7. <strong>Customer Feedback: </strong>Sending follow-up surveys to cart abandoners to understand why they didn’t complete the purchase may be a helpful for us to address common issues.</p><p>8. <strong>Loyalty Programs: </strong>Introducing a loyalty program that rewards users for completing a purchase after adding items to their cart could be a good marketing strategy.</p><p>9. <strong>Behavioural Analysis</strong>: Using <em>readable_timestam</em>p is always helpful in understanding the time between cart addition and abandonment or purchase. We can tailor our retargeting efforts based on this timing.</p><p>10. <strong>Product Bundle Offers:</strong> Offering bundled deals for products frequently added to carts together may likely increase the perceived value and encourage purchases.</p><h3><strong>Summary</strong></h3><p>BigQuery is a powerful platform for analyzing e-commerce behaviour for Google Analytics 4. Using the right queries, we can gain actionable insights to optimize our marketing tactics that could be used to reduce cart abandonment rate and increase conversion rate — <strong>the holy grail of a business.</strong></p><p><strong>Caveats:</strong> <em>The BigQuery public table for GA4 is obfuscated, which has many duplicates, deletions, null values, and not-set fields. Nevertheless, the sample queries used in examples can serve as a guide for pulling in details from your actual datasets. To ensure these queries work with your data, you may modify the query, adjust the table name and change the date ranges to suit your specific requirements.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d545d7f5ded" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redefining E-Commerce Analytics: The Synergy of GA4 and In-depth Statistical Analysis]]></title>
            <link>https://munaz-anjum.medium.com/redefining-e-commerce-analytics-the-synergy-of-ga4-and-in-depth-statistical-analysis-1437355387b6?source=rss-72567783a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/1437355387b6</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ga4]]></category>
            <dc:creator><![CDATA[Munaz Anjum]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 10:56:58 GMT</pubDate>
            <atom:updated>2023-10-15T11:32:53.628Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven e-commerce landscape, understanding user behavior is not just a necessity — it’s an art. Google Analytics 4 (GA4), a state-of-the-art analytics tool, offers a treasure trove of insights. But when combined with advanced statistical techniques, it transforms into a potent weapon for e-commerce businesses.</p><p>Let’s embark on this analytical journey using GA4 data from the table bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131.</p><h3><strong>1. Probability Analysis</strong></h3><p><strong>Event Probability Distribution:</strong></p><p>One of the primary methods to gauge user intent is by evaluating the probability distribution of events. For instance, consider tracking the “view_item” versus “add_to_cart” actions. Using BigQuery, we ascertain that the “view_item” event has a frequency of 1,829 (86.11%) and “add_to_cart” stands at 295 (13.89%). This disparity indicates that while many users show interest by viewing products, a smaller fraction progresses to adding items to their cart. Such insights can prompt businesses to enhance the user journey post-viewing, making the transition to purchase smoother.</p><pre>WITH EventCounts AS (<br>    SELECT<br>        event_name,<br>        COUNT(event_name) as event_count<br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`<br>    WHERE<br>        event_name IN (&quot;view_item&quot;, &quot;add_to_cart&quot;)<br>    GROUP BY<br>        event_name<br>)<br><br>SELECT<br>    event_name,<br>    event_count,<br>    event_count / SUM(event_count) OVER() as probability<br>FROM<br>    EventCounts;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*gf_uYnywiChsdIAZggyHxw.png" /></figure><p>Interpretation: The <em>view_item</em> event has been recorded 1,829 times, accounting for approximately <strong>86.11%</strong> of the events in the dataset.</p><p>The <em>add_to_cart</em> event has been recorded 295 times, accounting for approximately <strong>13.89% </strong>of the events in the dataset.</p><p>This suggests that a significant majority of user actions involve viewing items, while a smaller percentage involves adding items to the cart.</p><p><strong>Conditional Probability:</strong></p><p>Using the data:</p><p>Number of users who viewed an item = 1,829</p><p>Number of users who added an item to the cart after viewing = 295</p><p>Conditional Probability <em>(P(add_to_cart|view_item))</em> <em>= Number of users</em> who added an item to the cart after viewing / Number of users who viewed an item</p><p>= 295 / 1,829</p><p>≈ 0.1613 or 16.13%</p><p>This means that given a user viewed an item, there’s a 16.13% chance they added it to the cart.</p><p><strong>Interpretation:</strong> While a large percentage of users view items, only a smaller fraction of those users proceed to adding those items to their cart. This needs to deep dive further, such as looking at factors that might influence a user’s decision to add an item to their cart after viewing it.</p><p><strong>Assumptions</strong>: We’re assuming that the sequence of “view_item” followed by “add_to_cart” indicates a direct correlation, but external factors might influence user decisions. Secondly, the data is from a specific date (events_20210131), which may not represent typical user behavior. Seasonal variations, promotions, or even global events can sway these numbers.</p><h3><strong>2. Trends and Forecast Analysis</strong></h3><p><strong>a) Customers’ Daily Purchase Trend Analysis: Trends in Daily Purchase Totals Over Time</strong></p><p>Let’s delve into how customers’ purchases, have evolved over this period. Here’s an analysis using BigQuery:</p><pre>WITH DailyPurchaseTrends AS (<br>  SELECT<br>    EXTRACT(MONTH FROM DATE(TIMESTAMP_MICROS(event_timestamp))) AS month_number,<br>    EXTRACT(YEAR FROM DATE(TIMESTAMP_MICROS(event_timestamp))) AS year,<br>    DATE(TIMESTAMP_MICROS(event_timestamp)) AS event_date,<br>    SUM(items.item_revenue_in_usd) AS daily_purchase_value<br>  FROM<br>    `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,<br>    UNNEST(items) AS items<br>  WHERE<br>    DATE(TIMESTAMP_MICROS(event_timestamp)) BETWEEN &#39;2020-01-01&#39; AND &#39;2021-01-31&#39;<br>    AND event_name = &#39;purchase&#39;<br>  GROUP BY<br>    year, month_number, event_date<br>)<br><br>SELECT<br>  year,<br>  CASE month_number<br>    WHEN 1 THEN &#39;January&#39;<br>    WHEN 2 THEN &#39;February&#39;<br>    WHEN 3 THEN &#39;March&#39;<br>    WHEN 4 THEN &#39;April&#39;<br>    WHEN 5 THEN &#39;May&#39;<br>    WHEN 6 THEN &#39;June&#39;<br>    WHEN 7 THEN &#39;July&#39;<br>    WHEN 8 THEN &#39;August&#39;<br>    WHEN 9 THEN &#39;September&#39;<br>    WHEN 10 THEN &#39;October&#39;<br>    WHEN 11 THEN &#39;November&#39;<br>    WHEN 12 THEN &#39;December&#39;<br>    ELSE &#39;Unknown&#39;<br>  END AS month,<br>  event_date,<br>  SUM(daily_purchase_value) AS daily_purchase_total<br>FROM<br>  DailyPurchaseTrends<br>GROUP BY<br>  year, month_number, event_date<br>ORDER BY<br>  year, month_number, event_date;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QBvtOgfJ2ZQ8vT1H9UGOcQ.png" /></figure><p>Interpretation: The trend graph shows significant variability in daily purchase totals over the time frame, with two major peaks (one in mid-November and another in mid-December) followed by sharp declines. The reasons for these fluctuations could be influenced by various factors such as promotions, holidays, or external market conditions. To provide more specific insights, additional contextual information about the business or market would be necessary.</p><p>Statistical interpretation: For that, lets plot the graph in a box-plot.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>df = results</pre><pre>sns.boxplot(data=df, y=&#39;daily_purchase_total&#39;)<br>plt.xlabel(&#39;Daily Purchase Total&#39;)<br>plt.title(&#39;Box Plot of Daily Purchase Total&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fOgFRhwxty0Yw6vCyUOO4g.png" /></figure><p>In this box plot, we have checked the outlier using Z-scores for the ‘daily_purchase_total’, no specific points are plotted outside of the whiskers, so we can’t identify any outliers.</p><p><strong>The median daily purchase total (represented by the horizontal line within the box) appears to be around 5,000 units.</strong></p><p><strong>Most daily purchase totals (the central 50% of the data) lie between approximately 3,000 and 7,000 units, as indicated by the bottom and top of the box.</strong></p><p><strong>The smallest daily purchase total is slightly above 0, while the largest is near 12,000 units, as indicated by the ends.</strong></p><p>In a nutshell, there aren’t any evident outliers, suggesting that the data points are mostly within a predictable range without extreme deviations.</p><p>In conclusion, the company experiences a consistent middle ground of daily purchases, with occasional highs and lows. The absence of outliers suggests stable business operations without abrupt anomalies in daily sales.</p><p><strong>b) Forecasting:</strong></p><p>The next advanced concept is Forecasting. which is a critical component of decision-making in businesses, especially when it comes to understanding and predicting customer purchase behavior. We can use Prophet model for forecasting time series data, and it can be especially useful for data with strong seasonal effects and multiple seasons of historical data. It is robust to missing data and shifts in the trend, and typically handles outliers well. For our analysis, lets delve into this, however, the sample data too has caveats.</p><pre>!pip install pystan==2.19.1.1<br>!pip install prophet</pre><pre>from prophet import Prophet<br><br># Prepare the dataframe<br>df_prophet = df.reset_index().rename(columns={&#39;event_date&#39;: &#39;ds&#39;, &#39;daily_purchase_total&#39;: &#39;y&#39;})<br><br># Create and fit the Prophet model<br>model = Prophet(daily_seasonality=True)<br>model.fit(df_prophet.dropna())<br><br># Create a dataframe for future dates<br>future = model.make_future_dataframe(periods=30)<br><br># Forecast values<br>forecast = model.predict(future)<br><br># Extract the forecasted values for the next 30 days<br>forecasted_values = forecast[[&#39;ds&#39;, &#39;yhat&#39;, &#39;yhat_lower&#39;, &#39;yhat_upper&#39;]].tail(30)<br>print(forecasted_values)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*rvJNRU6Uvqfct8YqH0-hXg.png" /><figcaption>Foreacsted Values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*uLymKAcdustD168357RfoQ.png" /></figure><p>The forecast covered the period from 2021-01-31 to 2021-03-01, presenting predicted values alongside a range of lower and upper estimates. Some of the forecasts indicated potential negative values.</p><p><strong>Caveats:</strong></p><p>The primary goal of this solution is to illustrate the potential application of advanced statistical concepts within GA4. However, it doesn’t purport to be definitive or entirely accurate, given that the dataset hails from BigQuery’s public samples. Notably, our model has yielded negative values — a discrepancy that might not manifest when assessing proprietary data, depending on its quality. It’s paramount to remember that the realm of data analysis and forecasting is in constant flux, with methodologies and solutions that may be pertinent today becoming obsolete in the near future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1437355387b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ‘At-Risk’ and ‘Loyal’ Customers with GA4’s Public Data Using Clustering]]></title>
            <link>https://munaz-anjum.medium.com/understanding-at-risk-and-loyal-customers-with-ga4-s-public-data-using-clustering-3dbaad45411a?source=rss-72567783a912------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dbaad45411a</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[ga4]]></category>
            <dc:creator><![CDATA[Munaz Anjum]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 16:24:21 GMT</pubDate>
            <atom:updated>2023-10-11T17:37:50.601Z</atom:updated>
            <content:encoded><![CDATA[<p>Customer segmentation isn’t just about placing your customers into separate buckets but understanding how you can better serve them. When it comes to e-commerce, identifying ‘At-Risk’ and ‘Loyal’ customers is crucial. It informs retention strategies and helps businesses optimize customer lifetime value.</p><p>Using the GA4 public dataset on BigQuery, particularly from the bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_* table, we can make some informed classifications:</p><p><strong>Key Highlights:</strong></p><p>1. BigQuery and explore it with Google Colab (a Python Notebook)</p><p>2. Data Exploration &amp; Preprocessing</p><p>3. Establishing Recency, Frequency, Monetary (RFM) Metrics</p><p>4. Clustering with the K-means Algorithm</p><p>5. Insights &amp; Recommendations</p><h3>Extracting Data using BigQuery:</h3><p><strong>. </strong>Setting up BigQuery</p><p>· Navigate to the Google Cloud Console and select or create a project.</p><p>· Activate the BigQuery API for the project.</p><p>· <a href="https://console.cloud.google.com/bigquery?p=bigquery-public-data&amp;d=ga4_obfuscated_sample_ecommerce&amp;t=events_20210131&amp;page=table">Open the BigQuery Console</a> for sample dataset for Google Analytics 4</p><p>In the BigQuery Console, write the SQL query to extract the desired data.</p><p>Execute the query and ensure the results are as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*j0m35o0oX6U9D47B5l1dTw.png" /></figure><pre>#Public data has null value of user_id. Hence, we assume user_pseudo_id as users, however, you can use user_id to identify your customers.# You can use different parameters whatever you wish that makes sense for you!<br> <br>WITH <br>UserRecency AS (<br>    SELECT<br>        user_pseudo_id AS users,<br>        MAX(PARSE_DATE(&#39;%Y%m%d&#39;, event_date)) AS LastPurchaseDate<br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>    WHERE<br>        event_name = &#39;purchase&#39;<br>    GROUP BY<br>        users<br>),<br><br>UserFrequency AS (<br>    SELECT<br>        user_pseudo_id AS users,<br>        COUNT(*) AS PurchaseFrequency<br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>    WHERE<br>        event_name = &#39;purchase&#39;<br>    GROUP BY<br>        users<br>),<br><br>UserMonetaryValue AS (<br>    SELECT<br>        user_pseudo_id AS users,<br>        SUM(event_value_in_usd) AS TotalMonetaryValue<br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>    WHERE<br>        event_name = &#39;purchase&#39;<br>    GROUP BY<br>        users<br>),<br><br>UserGeographicLocation AS (<br>    SELECT<br>        user_pseudo_id AS users,<br>        MAX(geo.country) AS Country,  <br>        MAX(geo.city) AS City   <br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>    GROUP BY<br>        users<br>),<br><br>UserType AS (<br>    SELECT<br>        user_pseudo_id AS users,<br>        CASE<br>            WHEN MIN(event_date) = MAX(event_date) THEN &#39;New&#39;<br>            ELSE &#39;Returning&#39;<br>        END AS UserType<br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>    GROUP BY<br>        users<br>),<br><br>UserSource AS (<br>    SELECT<br>        user_pseudo_id AS users,<br>        MAX(traffic_source.`source`) AS Source  <br>    FROM<br>        `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`<br>    GROUP BY<br>        users<br>)<br><br>-- Combine features<br>SELECT<br>    R.users,<br>    R.LastPurchaseDate,<br>    F.PurchaseFrequency,<br>    M.TotalMonetaryValue,<br>    G.Country,<br>    G.City,<br>    T.UserType,<br>    S.Source<br>FROM<br>    UserRecency R<br>JOIN<br>    UserFrequency F USING (users)<br>JOIN<br>    UserMonetaryValue M USING (users)<br>JOIN<br>    UserGeographicLocation G USING (users)<br>JOIN<br>    UserType T USING (users)<br>JOIN<br>    UserSource S USING (users)<br></pre><h3>Initialize Google Colab &amp; Preprocess Data:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*Vr81PpUvqjj9G8tLxAZUKw.png" /></figure><p><strong>1.</strong> <strong>Import Libraries</strong>: Necessary Python libraries like pandas and StandardScaler from scikit-learn are imported.</p><p><strong>2.</strong> <strong>Load Data</strong>: It’s obvious that the data extracted from BigQuery has been loaded into a pandas DataFrame named <strong>results</strong>.</p><p><strong>3.</strong> <strong>Normalize the Data</strong>: StandardScaler is used to standardize the data (giving it a mean of 0 and a standard deviation of 1), which is essential for many machine learning algorithms, especially distance-based ones like KMeans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*aO6F_dFsUBNIGJTHKFsCKQ.png" /></figure><ol><li><strong>Import Libraries</strong>:</li></ol><pre># Import necessary libraries<br>import pandas as pd<br>from sklearn.preprocessing import StandardScaler</pre><p>2. <strong>Load Data</strong>:</p><pre>job = client.get_job(&#39;bquxjob_53ec7013_18b1e4b2d45&#39;) # Job ID inserted based on the query results selected to explore<br>results = job.to_dataframe()<br>results</pre><p>3. <strong>Data Normalization &amp; Handling of Missing Values</strong>:</p><pre>from sklearn.impute import SimpleImputer<br>imputer = SimpleImputer(strategy=&#39;mean&#39;)<br>results[numeric_columns] = imputer.fit_transform(results[numeric_columns])</pre><p><strong>Determining Optimal Clusters with Elbow Method:</strong> To cluster your data, first determine the best number of clusters:</p><pre>k = 3 <br>kmeans = KMeans(n_clusters=k, init=&#39;k-means++&#39;, random_state=42)<br>results[&#39;Cluster&#39;] = kmeans.fit_predict(results[numeric_columns])<br>print(results.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTCm_mQZorxGPfrRC3yPwA.png" /></figure><p><strong>Summarizing Clusters:</strong></p><p>By grouping by clusters, you can derive aggregate measures that describe each cluster’s characteristics:</p><pre>cluster_summary = results.groupby(&#39;Cluster&#39;).agg({<br>    &#39;LastPurchaseDate&#39;: [&#39;min&#39;, &#39;max&#39;],  # Getting range of purchase dates<br>    &#39;PurchaseFrequency&#39;: &#39;mean&#39;,<br>    &#39;TotalMonetaryValue&#39;: &#39;mean&#39;,<br>    &#39;Country&#39;: lambda x: x.value_counts().index[0],  # mode<br>    &#39;City&#39;: lambda x: x.value_counts().index[0],     # mode<br>    &#39;UserType&#39;: lambda x: x.value_counts().index[0], # mode<br>    &#39;Source&#39;: lambda x: x.value_counts().index[0]    # mode<br>}).reset_index()<br><br>print(cluster_summary) </pre><p><strong>Predict At-Risk’ and ‘Loyal’ Customers:</strong></p><pre> At-Risk Customers (Cluster 0)<br>at_risk_customers = results[results[&#39;Cluster&#39;] == 0][&#39;users&#39;]<br><br># Loyal Customers (Cluster 1)<br>loyal_customers = results[results[&#39;Cluster&#39;] == 1][&#39;users&#39;]<br><br># Print out the lists or save them<br>print(&quot;At-Risk Customers:\n&quot;, at_risk_customers)<br>print(&quot;\nLoyal Customers:\n&quot;, loyal_customers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*CHV3le8QJPljqrlF7DJG1w.png" /></figure><p><strong>Insights &amp; Recommendations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sssRiBURmXJptmCqOHln1A.png" /></figure><p><strong>Caveats:</strong></p><p>While the objective is to develop dependable clustering solutions using GA4 that aid businesses in forecasting their customer churn rate, several nuances must be noted. The approach, though rooted in clustering and churn prediction methodologies, is not without its challenges, inconsistency and considerations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dbaad45411a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>