<?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 MaranoSabrina on Medium]]></title>
        <description><![CDATA[Stories by MaranoSabrina on Medium]]></description>
        <link>https://medium.com/@maranosabrina9?source=rss-6bb18e636d19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ABofQyVpyjc5GPZjhRENKw.jpeg</url>
            <title>Stories by MaranoSabrina on Medium</title>
            <link>https://medium.com/@maranosabrina9?source=rss-6bb18e636d19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:51:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maranosabrina9/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[From dbt Tests to Data Observability: How Analytics Engineers Build Trustworthy Data Pipelines]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/from-dbt-tests-to-data-observability-how-analytics-engineers-build-trustworthy-data-pipelines-a34dba600151?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/0*IkoemAUVuefgqLtt.gif" width="600"></a></p><p class="medium-feed-snippet">A practical guide to dbt tests, Elementary Data, BigQuery assertions, and Looker alerts to keep your data healthy and clean and build&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/from-dbt-tests-to-data-observability-how-analytics-engineers-build-trustworthy-data-pipelines-a34dba600151?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/from-dbt-tests-to-data-observability-how-analytics-engineers-build-trustworthy-data-pipelines-a34dba600151?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34dba600151</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 13:03:17 GMT</pubDate>
            <atom:updated>2026-07-15T13:03:17.452Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Kafka to Snowflake: A Practical Guide to Real-Time and Semi-Structured Data]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/from-kafka-to-snowflake-a-practical-guide-to-real-time-and-semi-structured-data-54eb3569d121?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/0*B2R5lwgCm4nPM7BZ.gif" width="600"></a></p><p class="medium-feed-snippet">A hands-on tutorial for handling streams &#x2014; and the messy JSON they arrive as</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/from-kafka-to-snowflake-a-practical-guide-to-real-time-and-semi-structured-data-54eb3569d121?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/from-kafka-to-snowflake-a-practical-guide-to-real-time-and-semi-structured-data-54eb3569d121?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/54eb3569d121</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 14:14:42 GMT</pubDate>
            <atom:updated>2026-07-13T14:14:54.924Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Get Started with Database Design and Data Warehouse Modelling]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/get-started-with-database-design-and-data-warehouse-modelling-3392fc0c8a98?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/1*axM6zpcDNJPyi7xF84td7A.gif" width="600"></a></p><p class="medium-feed-snippet">The Alice journey: a useful beginner-friendly introduction with SQL snippets using Databricks</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/get-started-with-database-design-and-data-warehouse-modelling-3392fc0c8a98?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/get-started-with-database-design-and-data-warehouse-modelling-3392fc0c8a98?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/3392fc0c8a98</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 15:25:25 GMT</pubDate>
            <atom:updated>2026-07-12T15:25:25.030Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[What Would You Build as a Retailer’s First Data Engineer? Here’s My Answer]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/what-would-you-build-as-a-retailers-first-data-engineer-here-s-my-answer-9786bd58633b?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/0*Z1IhWwh802v1FCi5.gif" width="600"></a></p><p class="medium-feed-snippet">Building a marketing data pipeline from scratch with MySQL, Snowflake, dbt, Airflow, Docker and Looker Studio &#x2014; with the code, the design&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/what-would-you-build-as-a-retailers-first-data-engineer-here-s-my-answer-9786bd58633b?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/what-would-you-build-as-a-retailers-first-data-engineer-here-s-my-answer-9786bd58633b?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/9786bd58633b</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 13:55:07 GMT</pubDate>
            <atom:updated>2026-07-12T13:55:07.718Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Handy ML Part 2: All you have to know about ML basics]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/handy-ml-part-2-all-you-have-to-know-about-ml-basics-50147dc1c797?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/0*V2Mc1jFLSNMQU43Q.gif" width="600"></a></p><p class="medium-feed-snippet">Crucial steps behind the scenes</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/handy-ml-part-2-all-you-have-to-know-about-ml-basics-50147dc1c797?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/handy-ml-part-2-all-you-have-to-know-about-ml-basics-50147dc1c797?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/50147dc1c797</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 16:14:54 GMT</pubDate>
            <atom:updated>2025-07-27T15:55:51.485Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Handy ML Part 1: All you have to know about ML basics]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/handy-ml-part-1-all-you-have-to-know-about-ml-basics-ec84ec6a90c2?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/0*NVzDxxIqVLLoqATP.gif" width="600"></a></p><p class="medium-feed-snippet">Practical guide to step into Machine Learning algorithms</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/handy-ml-part-1-all-you-have-to-know-about-ml-basics-ec84ec6a90c2?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/handy-ml-part-1-all-you-have-to-know-about-ml-basics-ec84ec6a90c2?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec84ec6a90c2</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 15:48:08 GMT</pubDate>
            <atom:updated>2025-07-27T15:29:41.516Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Companies list hiring remotely (Feb 2025)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Looking for a new job in these tough times is hard but sharing is caring, isn&#x2019;t?</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/companies-list-hiring-remotely-feb-2025-fb63d5fad6f5?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/companies-list-hiring-remotely-feb-2025-fb63d5fad6f5?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb63d5fad6f5</guid>
            <category><![CDATA[job-hunting]]></category>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 09:12:43 GMT</pubDate>
            <atom:updated>2025-02-18T10:39:15.383Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Handy Statistics Part 4: All you have to know about Causal Inference]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@maranosabrina9/handy-statistics-part-4-all-you-have-to-know-about-causal-inference-74fe4db0fbfa?source=rss-6bb18e636d19------2"><img src="https://cdn-images-1.medium.com/max/600/0*B581Xvz4r3QwZDXJ.gif" width="600"></a></p><p class="medium-feed-snippet">A complete easy guide explained with Python code and examples</p><p class="medium-feed-link"><a href="https://medium.com/@maranosabrina9/handy-statistics-part-4-all-you-have-to-know-about-causal-inference-74fe4db0fbfa?source=rss-6bb18e636d19------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@maranosabrina9/handy-statistics-part-4-all-you-have-to-know-about-causal-inference-74fe4db0fbfa?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/74fe4db0fbfa</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 15:04:23 GMT</pubDate>
            <atom:updated>2025-07-25T16:30:29.548Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Handy Statistics Part 3: All you have to know about Inferential Statistics]]></title>
            <link>https://medium.com/@maranosabrina9/handy-statistics-part-3-all-you-have-to-know-about-inferential-statistics-a6566d5f8899?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6566d5f8899</guid>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 11:50:58 GMT</pubDate>
            <atom:updated>2025-07-25T15:47:54.000Z</atom:updated>
            <content:encoded><![CDATA[<p>A complete easy guide explained with Python code and examples</p><p>Hey there! Welcome to the third part of the “Handy Statistics” series!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*M0WSbI4N4M_qyOvv.gif" /></figure><p>Today, we will dive deep into inferential statistics. In case you have missed the other two parts, you can go <a href="https://medium.com/@maranosabrina9/handy-statistics-part-2-all-you-have-to-know-about-descriptive-statistics-32d70ab97741">here</a> and <a href="https://medium.com/@maranosabrina9/handy-statistics-part-1-types-of-statistics-in-data-science-and-why-they-are-so-important-1b138baa0e95">here</a>.</p><p>In detail, we will talk about:</p><ul><li>probability theory in inferential statistics</li><li>what is a sample and what are the different techniques used to extrapolate it from the population</li><li>probability distributions and their purpose in this case</li><li>the beauty of hypothesis testing and which conclusions we can draw from the tests</li><li>a huge deep dive regarding tests and their relative tables and scores</li></ul><h3>1. Introduction</h3><p>As we saw in the first part, inferential statistics is selected when we aim to make inferences or generalizations about a population based on a sample. How many times and in how many articles and books have you read this sentence? I bet millions. But what does it mean?</p><p>In practical terms, we use inferential statistics when:</p><ul><li>we want to <strong>test</strong> if “something new” e.g a marketing strategy, product feature etc. <strong>affects</strong> our target based on our hypothesis like “the new campaign increases sales” (Hypothesis Testing: Statistical Tests — to evaluate whether the observed effect is statistically significant or due to chance)</li><li>we want to <strong>check</strong> if there is a correlation between two variables, such as ad spend and customer acquisitions (Hypothesis Testing: Correlation — Testing if the correlation coefficient is significantly different from zero)</li><li>we want to <strong>compare</strong> variables on the target variable like the effectiveness of two product page designs on conversion rates ((Hypothesis Testing: Comparative Tests - testing if the means or proportions of the target variable differ significantly between groups)</li><li>we want to <strong>estimate probabilities</strong> like the probability of a customer purchasing after interacting with a chatbot and/or <strong>parameters</strong> like the satisfaction score for a new product feature (Probability Distribution — estimate the likelihood of an event occurring or estimate parameters of a population )</li></ul><p>But how does the sample population work in these scenarios? Taking data from the entire population would be amazing, but often it is <strong>not feasible</strong> because it can be <strong>costly</strong>, <strong>time-consuming</strong>, and <strong>logistically challenging</strong>. Here are the main reasons why using a sample is preferred over the entire population:</p><ol><li><strong>Cost Efficiency: </strong>full population sampling involves significant costs, such as surveying or collecting data from every individual in the population (e.g if you want to survey all users of a new product feature, you might have thousands or even millions of customers. Collecting data from all of them could require expensive tools, staff, or resources, which is often not practical.</li><li><strong>Time Constraints: </strong>Surveying the entire population can take a <strong>long time</strong>. You may need to wait for responses from all users, which delays your analysis and decision-making. Using a sample allows you to gather data faster and make quicker decisions.</li><li><strong>Data Collection Challenges and Practicality: </strong>Reaching every individual can be difficult or impossible, besides the costs and the time we saw mentioned above. Some users may not respond to surveys, or it might be hard to access all of them. A sample can be <strong>representative</strong> of the<strong> </strong>population without needing to contact every single person.</li></ol><p>So inferential statistics allows us to make valid conclusions about the <strong>entire population</strong> based on data from a <strong>sample</strong>. Using the appropriate methods (like confidence intervals and hypothesis tests) based on the case, we can estimate the population parameters (like the average satisfaction score) with a known level of <strong>certainty</strong> or <strong>confidence, </strong>within a certain margin of error.</p><h4>Key concepts to keep in mind</h4><p>Before showing the core of inferential statistics, it is necessary to illustrate some key concepts we will encounter throughout this blog post, what they are, their purpose, how to interpret them and how they are connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Cp72Sul5MLFh9SZ3n4VltQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*C2lSlpYJ7D_4XA9DDAjTcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Wi7D21MlyCkvc9OnqgXIXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*jHRR99wAOimpt-TbfHf6LQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*mq1-vxjF3r_-XdyeElWECA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*Ej0A7eGu8VMc40Z-wwS1fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*IHRd3o_wABb7gLMioUaOvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*TmXPu3V1bH1Mf4QzbVUAzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*SbzRMQYZhShrzJMdAs2RLw.png" /></figure><p>You’re welcome!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*vyqTbqhtKGt0l_ll.gif" /></figure><p>Following the Python code to calculate them:</p><pre>import numpy as np<br>import scipy.stats as stats<br>import statsmodels.stats.api as sms<br><br># Function to calculate confidence interval (CI)<br>def calculate_confidence_interval(mean, std_dev, n, confidence_level=0.95):<br>    alpha = 1 - confidence_level<br>    z = stats.norm.ppf(1 - alpha / 2)  # Z critical value for confidence interval<br>    margin_of_error = z * (std_dev / np.sqrt(n))<br>    ci_lower = mean - margin_of_error<br>    ci_upper = mean + margin_of_error<br>    return ci_lower, ci_upper<br><br># Function to calculate p-value<br>def calculate_p_value(test_statistic, df, test_type=&#39;two-tailed&#39;):<br>    if test_type == &#39;two-tailed&#39;:<br>        p_value = 2 * (1 - stats.t.cdf(abs(test_statistic), df))<br>    elif test_type == &#39;one-tailed&#39;:<br>        p_value = 1 - stats.t.cdf(test_statistic, df)<br>    return p_value<br><br># Function to calculate z-score<br>def calculate_z_score(x, mean, std_dev):<br>    return (x - mean) / std_dev<br><br># Function to calculate power of the test (for a two-sample test)<br>def calculate_power(effect_size, alpha=0.05, n=50, alternative=&#39;two-sided&#39;):<br>    power_analysis = sms.TTestIndPower()<br>    power = power_analysis.solve_power(effect_size=effect_size, nobs1=n, alpha=alpha, ratio=1.0, alternative=alternative)<br>    return power<br><br># Function to calculate critical value (z or t) example<br>def calculate_critical_value(alpha, distribution=&#39;z&#39;, df=None):<br>    if distribution == &#39;z&#39;:<br>        return stats.norm.ppf(1 - alpha / 2)<br>    elif distribution == &#39;t&#39; and df is not None:<br>        return stats.t.ppf(1 - alpha / 2, df)<br>    else:<br>        raise ValueError(&#39;Invalid distribution type or missing degrees of freedom.&#39;)<br><br># Function to calculate standard error<br>def calculate_standard_error(std_dev, n):<br>    return std_dev / np.sqrt(n)<br><br># Function to calculate margin of error<br>def calculate_margin_of_error(critical_value, std_err):<br>    return critical_value * std_err<br><br># Function to calculate minimum detectable effect (MDE)<br>def calculate_mde(std_dev, alpha=0.05, power=0.8, n=50):<br>    effect_size = sms.TTestIndPower().solve_power(alpha=alpha, power=power, nobs1=n)<br>    mde = effect_size * std_dev<br>    return mde<br><br># Example usage:<br>mean = 100<br>std_dev = 15<br>n = 30<br>confidence_level = 0.95<br>alpha = 0.05<br>x = 110  # Sample point for z-score calculation<br>df = n - 1<br><br># Confidence Interval<br>ci_lower, ci_upper = calculate_confidence_interval(mean, std_dev, n, confidence_level)<br>print(f&quot;Confidence Interval: ({ci_lower}, {ci_upper})&quot;)<br><br># Z-score<br>z_score = calculate_z_score(x, mean, std_dev)<br>print(f&quot;Z-score: {z_score}&quot;)<br><br># Power of the test<br>effect_size = 0.5  # Cohen&#39;s d<br>power = calculate_power(effect_size, alpha, n)<br>print(f&quot;Statistical Power: {power}&quot;)<br><br># Critical value (Z)<br>z_critical = calculate_critical_value(alpha)<br>print(f&quot;Z Critical Value: {z_critical}&quot;)<br><br># Standard Error<br>standard_error = calculate_standard_error(std_dev, n)<br>print(f&quot;Standard Error: {standard_error}&quot;)<br><br># Margin of Error<br>margin_of_error = calculate_margin_of_error(z_critical, standard_error)<br>print(f&quot;Margin of Error: {margin_of_error}&quot;)<br><br># Minimum Detectable Effect (MDE)<br>mde = calculate_mde(std_dev, alpha, power, n)<br>print(f&quot;Minimum Detectable Effect (MDE): {mde}&quot;)<br><br># P-value for a sample t-test<br>test_statistic = 2.5  # Example test statistic<br>p_value = calculate_p_value(test_statistic, df)<br>print(f&quot;P-value: {p_value}&quot;)<br></pre><p><strong>output:</strong></p><pre>Confidence Interval: (94.63241756884852, 105.36758243115148)<br>Z-score: 0.6666666666666666<br>Statistical Power: 0.4778965200281735<br>Z Critical Value: 1.959963984540054<br>Standard Error: 2.7386127875258306<br>Margin of Error: 5.3675824311514715<br>Minimum Detectable Effect (MDE): 7.499998030400507<br>P-value: 0.01832534433842614</pre><p>Ok, now you can thank me</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*ypWEu9C5wAC13bai.gif" /></figure><h3>2. Probability theory</h3><p>Inferential statistics has its foundation in probability theory. Probability is a mathematical framework for quantifying uncertainty, representing the likelihood of events occurring, and modelling the randomness of the variables. In general, probability means how likely something is to happen, expressed as a number between 0 and 1.</p><p>How does probability theory have its spot in inferential statistics? Let’s look at some cases.</p><ol><li><strong>Randomness and Sampling</strong></li></ol><p>Randomness ensures a fair and unbiased sample selection, which is critical for generalizing to the population.</p><p><strong>Probability Rule Used</strong>: S<strong>imple Random Sampling</strong> — Each member of the population has an equal probability of being selected, ensuring the sample represents the population without bias.</p><p><strong>2. Uncertainty and Representation</strong></p><p>Since we can’t observe the entire population, we use probability to quantify how likely sample results are to reflect the population, in other words, if the sample is representative of the entire population.</p><p><strong>Probability Rule Used</strong>: <strong>Law of Large Numbers</strong> — Larger sample sizes make sample statistics converge closer to the population statistics.</p><p><strong>3. Hypothesis Testing</strong></p><p>Hypothesis testing evaluates whether observed differences in the sample (e.g., new vs. old product) are likely due to random chance.</p><p><strong>Probability Rule Used</strong>: <strong>Conditional Probability</strong> — Determines the probability of observing the data assuming the null hypothesis is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*Q2gZwe8q2qWwbWaOwm_dtw.png" /></figure><p><strong>4. Random Variables and Distributions</strong></p><p>Each data point in the sample represents a random outcome, and probability distributions model these outcomes.</p><p><strong>Probability Rule Used</strong>: <strong>Addition Rule and Multiplication Rule and Probability Distributions </strong>— Used for combining probabilities of different outcomes.</p><p><strong>5. P-Values and Significance Testing</strong></p><p>P-values assess the strength of evidence against the null hypothesis, by quantifying the probability of observing the data, or data more extreme, assuming the null hypothesis is true.</p><p><strong>Probability Rule Used</strong>: <strong>Cumulative Probability</strong> — Measuring the total probability of observing values as extreme or more extreme than the test statistic in the relevant tails of the distribution</p><h3>3. Sampling Techniques</h3><p>But how do we get this famous sample from a population that has all the characteristics to be representative of our population for us to draw conclusions?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*67fnamQ1zIP48bpb.gif" /></figure><p>Sampling methods are broadly categorized into <strong>probability sampling</strong> and <strong>non-probability sampling</strong>.</p><p>In probability sampling, every member of the population has a known, non-zero chance of being selected <strong>randomly</strong>, which supports unbiased representation and statistical inference.</p><ol><li><strong>Simple Random Sampling</strong>: Each individual has an equal probability of being chosen. This can be achieved using random number generators or drawing lots.</li><li><strong>Systematic Sampling</strong>: Selection of every <em>k-th</em> individual from a list after a random starting point. For example, choosing every 10th person on an alphabetical list.</li><li><strong>Stratified Sampling</strong>: The population is divided into homogeneous subgroups (strata) based on specific characteristics (e.g., age, gender), and random samples are drawn from each stratum proportionally, ensuring equal chances of being selected.</li><li><strong>Cluster Sampling</strong>: The population is divided into clusters, often based on geography or organization. Entire clusters are randomly selected, and all members within chosen clusters are surveyed.</li></ol><p>In non-probability sampling, not all members have a chance of being included, which can introduce bias but may be practical in exploratory research.</p><ol><li><strong>Convenience Sampling</strong>: Selecting readily available individuals, such as surveying passersby in a mall.</li><li><strong>Judgmental or Purposive Sampling</strong>: Researchers use their judgment to select participants who are deemed representative or possess specific characteristics.</li><li><strong>Snowball Sampling</strong>: Existing participants recruit future subjects from among their acquaintances, useful for accessing hard-to-reach populations.</li><li><strong>Quota Sampling</strong>: Ensuring the sample meets certain quotas regarding characteristics like age, gender, or education level, without random selection.</li></ol><h4><strong>Sampling Bias</strong></h4><p>Sampling bias occurs when the sample does not accurately represent the population, leading to skewed results and limiting the generalizability of findings.</p><p><strong>Types of Sampling Bias</strong></p><ol><li><strong>Selection Bias</strong>: Systematic exclusion or overrepresentation of certain groups. For instance, conducting an online survey may exclude individuals without internet access.</li><li><strong>Non-Response Bias</strong>: Significant differences between those who respond to a survey and those who do not, potentially skewing results.</li><li><strong>Undercoverage Bias</strong>: Some population segments are inadequately represented in the sample.</li><li><strong>Voluntary Response Bias</strong>: Individuals with strong opinions are more likely to participate, which can distort findings.</li><li><strong>Measurement Bias</strong>: Errors in data collection methods, such as leading questions or inaccurate measurements, affect the validity of results.</li></ol><h4><strong>Sample Size</strong></h4><p>Determining the appropriate sample size is crucial for the reliability and validity of study results.</p><p>Some aspects we have to consider related to the sample size are:</p><ol><li><strong>Population Size</strong>: While larger populations may require larger samples, the increase in sample size beyond a certain point yields diminishing returns.</li><li><strong>Margin of Error</strong>: The acceptable range within which the true population parameter is expected to fall.</li><li><strong>Confidence Level</strong>: The probability that the sample accurately reflects the population parameter, commonly set at 95% or 99%.</li><li><strong>Variability</strong>: Greater variability within the population necessitates a larger sample to accurately capture the diversity.</li><li><strong>Resource Constraints</strong>: Time, budget, and personnel availability can influence feasible sample sizes.</li><li><strong>Desired Precision: </strong>Higher precision (lower margin of error) requires a larger sample.</li><li><strong>Statistical Power: </strong>Power measures the probability of detecting an effect if it exists (commonly set at 80%).</li></ol><p><strong>Sample Size Calculation</strong></p><p>When possible, we can calculate the sample size to ensure valid results.</p><p>For large populations, the sample size<em> n proportion </em>can be estimated using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDPhGR-BncT3U5c5qDT-ww.png" /></figure><p>For finite populations, adjust the sample size using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2S5Cy6EIQd2qxTIolZ115g.png" /></figure><h3>4. Probability Distributions</h3><p>Do you remember when we said, “we use inferential statistics when we want to <strong>estimate probabilities</strong> like the probability of a customer purchasing after interacting with a chatbot and/or <strong>parameters</strong> like the satisfaction score for a new product feature”?</p><p>Here it is when the probability distributions play a crucial role.</p><p>In boring terms, a probability distribution is a mathematical function that describes the likelihood of different outcomes or values of a random variable. Meaning, it tells you how probabilities are distributed across the possible values that a variable can take.</p><p>In funnier terms, imagine a restaurant that serves only burgers. They don’t just have one type of burger; they have a whole menu with different sizes and toppings, which affects the price.</p><ul><li><strong>The Menu (Possible Outcomes):</strong> The menu lists all the possible burgers you can order. This is like the range of values a variable can take in a probability distribution. It could be small, medium, large, double, etc.</li><li><strong>The Popularity of Each Burger (Probability):</strong> Some burgers are more popular than others. The classic cheeseburger might be ordered most often, while the triple bacon burger is ordered less frequently. This “popularity” is like the probability of each value occurring in a distribution.</li></ul><p><strong>Different “Restaurant Styles” (Types of Distributions):</strong></p><p>Different restaurants have different styles, just like there are different types of probability distributions:</p><ul><li><strong>Classic Diner (Normal Distribution):</strong> This diner specializes in classic burgers. Most of their burgers are around a medium size and a medium price. They have a few smaller and cheaper burgers and a few larger and more expensive ones, but those are less common. This is like a normal distribution — most values are clustered around the average. The “bell curve” is like a graph of their menu items by price and how often they’re ordered.</li><li><strong>Budget Burger Joint (Uniform Distribution):</strong> This place only sells one size of burger at one price. Every burger is exactly the same. This is like a uniform distribution — every outcome (burger) is equally likely.</li><li><strong>Gourmet Burger Bistro (Skewed Distribution):</strong> This bistro has a wide range of burgers, from small, simple ones to massive, gourmet creations with exotic toppings. Most of their burgers are on the higher end of the price scale, with only a few cheaper options. This is like a skewed distribution — most values are concentrated on one side (higher prices).</li></ul><p>But not only! They also want to know the “traffic” in the restaurant to be prepared on crowded days.</p><ul><li><strong>Busy Hour Rush (Poisson Distribution):</strong> This distribution doesn’t describe the <em>burgers</em> themselves, but rather <em>how many customers arrive per hour with the intent of enjoying the burgers</em></li><li><strong>Customer Satisfaction (Binomial Distribution):</strong> Now, let’s say we survey every 10th customer and ask if they were “satisfied” or “not satisfied” with their meal. The binomial distribution helps us understand the probability of getting a certain number of satisfied customers out of that group of 10.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*iFr5pSYsIrWj-U-n.gif" /></figure><p>The key components of the probability distribution are:</p><ol><li><strong>Random Variable</strong>:</li></ol><ul><li>A variable that takes on different values, each associated with a probability.</li><li>Can be <strong>discrete</strong> (e.g., the number of heads in coin tosses) or <strong>continuous</strong> (e.g., the height of individuals).</li></ul><p><strong>2. Types of Probability Distributions</strong>:</p><ul><li><strong>Discrete Distributions</strong>: Defined by a <strong>Probability Mass Function (PMF)</strong>.</li><li><strong>Continuous Distributions</strong>: Defined by a <strong>Probability Density Function (PDF)</strong>.</li></ul><p>In this blog post, we will investigate only:</p><p>Discrete:</p><ul><li>Binomial Distribution</li><li>Poisson Distribution</li><li>Bernoulli Distribution</li><li>Geometric Distribution</li></ul><p>Continuous:</p><ul><li>Normal Distribution</li><li>Uniform Distribution</li><li>Exponential Distribution</li></ul><h4>Discrete distributions:</h4><p><strong>Binomial Distribution</strong></p><p>The binomial distribution is a discrete probability distribution that models the number of successes in a fixed number of trials, each with two possible outcomes: success or failure. It is used when the following conditions are met:</p><ol><li><strong>Fixed Number of Trials</strong>: The experiment is conducted a specific number of times, denoted as n.</li><li><strong>Two Possible Outcomes</strong>: Each trial has two possible outcomes: “success” (1) or “failure” (0).</li><li><strong>Constant Probability of Success</strong>: The probability of success on each trial is constant and denoted as p.</li><li><strong>Independence</strong>: Each trial is independent of others.</li></ol><p>The probability of exactly k successes in n trials in a binomial distribution is given by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcvJUIGQT0WLKOXylVBIxQ.png" /></figure><p>Let me explain with practical examples:</p><p><strong>Marketing Example:</strong></p><p>Imagine a company running an email campaign that expects 10% of the recipients to purchase after receiving an email. If the company sends the email to 100 people, what is the probability that exactly 12 people will make a purchase?</p><ul><li>n=100 (number of trials),</li><li>k=12 (number of successes),</li><li>p=0.10 (probability of success, i.e., a person making a purchase).</li></ul><pre>#Marketing Example <br>n_marketing = 100  # Number of customers<br>p_marketing = 0.10  # Probability of email being opened<br>k_marketing = 10  # Example number of customers opening the email<br><br>probability_marketing = binom.pmf(k_marketing, n_marketing, p_marketing)<br>print(f&quot;Marketing Example: Probability of exactly {k_marketing} customers opening the email: {probability_marketing:.10f}&quot;)<br><br># Plotting the marketing example<br>x_marketing = np.arange(0, n_marketing + 1)<br>pmf_values_marketing = binom.pmf(x_marketing, n_marketing, p_marketing)<br><br>plt.figure(figsize=(10,6))<br>plt.bar(x_marketing, pmf_values_marketing, color=&#39;orange&#39;, alpha=0.7)  <br>plt.title(f&quot;Marketing Email Open Rate (n={n_marketing}, p={p_marketing})&quot;)<br>plt.xlabel(&quot;Number of Customers Opening Email&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*GKHyjFbbCfmOgXqZ7Wl3iw.png" /></figure><p><strong>Product Example:</strong></p><p>You’re running a digital product subscription service (for example, an online course platform). You know that the probability of a user subscribing to a premium plan after a free trial is 15%. If you have 200 users who start the free trial, what is the probability that exactly 30 users will subscribe to the premium plan?</p><p>Here:</p><ul><li>n=200 (number of trials, i.e., number of users),</li><li>p=0.15 (probability of success, i.e., a user subscribing),</li><li>k=30 (number of successes, i.e., number of users subscribing).</li></ul><pre># Product Example<br>n_digital = 200  # Number of free-trial users<br>p_digital = 0.15  # Probability of subscribing to premium<br>k_digital = 30  # Example number of users subscribing to premium<br><br>probability_digital = binom.pmf(k_digital, n_digital, p_digital)<br>print(f&quot;Digital Product Example: Probability of exactly {k_digital} users subscribing to premium: {probability_digital:.4f}&quot;)<br><br># 2. Plot the digital product example<br>x_digital = np.arange(0, n_digital + 1)  # All possible outcomes<br>pmf_values_digital = binom.pmf(x_digital, n_digital, p_digital)<br><br>plt.figure(figsize=(10, 6))<br>plt.bar(x_digital[:50], pmf_values_digital[:50], color=&#39;purple&#39;, alpha=0.7)  # First 50 bars for clarity<br>plt.title(f&quot;Digital Product Premium Subscription (n={n_digital}, p={p_digital})&quot;)<br>plt.xlabel(&quot;Number of Users Subscribing&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*6k3voQUut-_cEydSYisJNg.png" /></figure><p><strong>Poisson Distribution</strong></p><p>The <strong>Poisson distribution</strong> models the number of events occurring in a fixed interval of time or space, given a known average rate (λ) of occurrence.</p><p>Key Properties of Poisson Distribution:</p><ol><li><strong>Mean and Variance:</strong> Both are equal to λ.</li><li><strong>Discrete Distribution:</strong> Only non-negative integer values (k=0,1,2,…) are possible.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mObSwbV-nT_HtaMEmcd5-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hR6bfDwM3f55skSgiOxayw.png" /></figure><p>Let me explain with practical examples:</p><p><strong>Marketing Example:</strong></p><p>Imagine a call center where customer inquiries are logged hourly. Over 5 days, the center receives 120 inquiries. The question is:<br><strong>What is the probability of receiving exactly 5 inquiries in an hour?</strong></p><ul><li>λ=120/(5×24)= 1 (average inquiries per hour).</li><li>k=5 (number of inquiries of interest).</li></ul><pre># --- Marketing Example ---<br>lambda_marketing = 1  # Average inquiries per hour<br>k_marketing = 5  # Number of inquiries of interest<br><br>probability_marketing = poisson.pmf(k_marketing, lambda_marketing)<br>print(f&quot;Marketing Example: Probability of exactly {k_marketing} inquiries in an hour: {probability_marketing:.4f}&quot;)<br><br><br># Plot the Poisson distribution for marketing example<br>x = np.arange(0, 6)  # Range of possible outcomes (e.g., 0 to 14 inquiries)<br>pmf_values = poisson.pmf(x, lambda_marketing)  # Calculate PMF for each value of x<br><br>plt.figure(figsize=(10, 6))<br>plt.bar(x, pmf_values, color=&#39;skyblue&#39;, alpha=0.7)<br>plt.title(&quot;Marketing Example: Customer Inquiries per Hour&quot;)<br>plt.xlabel(&quot;Number of Events (k)&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*j6LxAp2XGm__XrvWdigCog.png" /></figure><p>or</p><p>You are running a marketing campaign where you send an email to <strong>50 customers</strong>, and based on past experience, you expect an average of <strong>2 people</strong> to make a purchase. Now, you want to simulate how many purchases you might get in <strong>this specific campaign. (</strong>assuming the number of purchases follows a Poisson distribution)</p><pre># Given parameters<br>lambda_marketing = 2  # Average number of purchases (λ)<br>num_customers = 50    # Number of customers in the current campaign<br><br># Simulate the number of purchases for the current campaign<br>simulated_purchases = poisson.rvs(lambda_marketing)<br><br># Output the simulated number of purchases<br>print(f&quot;Simulated number of purchases in the current campaign: {simulated_purchases}&quot;)<br>Simulated number of purchases in the current campaign: 2</pre><p><strong>Product Example:</strong></p><p>Suppose a cloud hosting company observes an average of 36 server crashes over 12 months. The question is:<br><strong>What is the probability of exactly 2 crashes in a specific month?</strong></p><ul><li>λ=36/12=3 (average crashes per month).</li><li>k=2 (number of crashes of interest).</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import poisson<br><br># Product Example <br>lambda_product = 3  # Average crashes per month<br>k_product = 2  # Number of crashes of interest<br><br>probability_product = poisson.pmf(k_product, lambda_product)<br>print(f&quot;Product Example: Probability of exactly {k_product} crashes per month: {probability_product:.4f}&quot;)<br><br><br># Plot the Poisson distribution for marketing example<br>x = np.arange(0, 6)  # Range of possible outcomes (e.g., 0 to 14 inquiries)<br>pmf_values = poisson.pmf(x, lambda_product)  # Calculate PMF for each value of x<br><br>plt.figure(figsize=(10, 6))<br>plt.bar(x, pmf_values, color=&#39;skyblue&#39;, alpha=0.7)<br>plt.title(&quot;Product Example: Server Crashes per Month&quot;)<br>plt.xlabel(&quot;Number of Events (k)&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*WVahfZgXmPno_4aNLT3-qg.png" /></figure><p><strong>Bernoulli Distribution</strong></p><p>The <strong>Bernoulli distribution</strong> describes the probability of a binary outcome in a single trial or experiment. The possible outcomes are typically referred to as success (1) or failure (0). The difference with Binomial is the number of trials. Each trial is a Bernoulli experiment (success or failure), and the binomial distribution models how many successes you have in a fixed number of such trials.</p><p><strong>Key Properties:</strong></p><ul><li>The <strong>mean</strong> of the Bernoulli distribution is μ=p.</li><li>The <strong>variance</strong> is σ2=p(1−p).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqH4H2km1emVXtGNmrysEQ.png" /></figure><p><strong>Marketing example:</strong></p><p>Imagine you’re testing a new marketing email campaign. You send the email to one customer and are interested in whether they open the email or not. (Quite unrealistic that you will test only one customer but just the get the idea)</p><ul><li>A <strong>success</strong> (1) is the customer opening the email.</li><li>A <strong>failure</strong> (0) is the customer not opening the email.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import bernoulli<br><br>#Past data<br>total_emails_sent = 100<br>emails_opened = 35<br><br># Estimating probability of success (p)<br>p_estimated = emails_opened / total_emails_sent<br>print(f&quot;Estimated probability of success (email opened): {p_estimated:.4f}&quot;)<br><br>k = 1  # We want to know the probability of success (email opened)<br><br># 1. Calculate the probability of success (email opened)<br>prob_success = bernoulli.pmf(k, p_estimated)<br>print(f&quot;Probability of success (email opened): {prob_success:.4f}&quot;)<br><br># 2. Calculate the probability of failure (email not opened)<br>prob_failure = bernoulli.pmf(0, p_estimated)<br>print(f&quot;Probability of failure (email not opened): {prob_failure:.4f}&quot;)<br><br>labels = [&#39;Failure (0)&#39;, &#39;Success (1)&#39;]<br>values = [prob_failure, prob_success]<br><br><br># Plotting the distribution of results (Success vs Failure)<br>plt.figure(figsize=(8, 5))<br>plt.bar(labels, values, color=[&#39;lightcoral&#39;, &#39;skyblue&#39;], alpha=0.7)<br>plt.title(f&quot;Probability Distribution for Email Open (Bernoulli Distribution, p={p_estimated:.2f})&quot;)<br>plt.xlabel(&quot;Outcome&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.grid(True, axis=&#39;y&#39;, linestyle=&#39;--&#39;, alpha=0.6)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*pc42yqR7Z0u9wvp1FdsClw.png" /></figure><p><strong>Geometric Distribution</strong></p><p>The <strong>Geometric Distribution</strong> models the number of trials required until the first success in a series of independent Bernoulli trials or the probability of success at fixed k. It is memoryless, meaning that the probability of success on the next trial does not depend on the outcome of previous trials.</p><p><strong>Key Characteristics:</strong></p><ul><li><strong>Memoryless Property</strong>: The probability of the first success occurring after k trials does not depend on how many trials have already occurred. This means the distribution does not “remember” past failures.</li><li><strong>Mean</strong>: The expected number of trials to get the first success is 1/p​, where p is the probability of success on each trial.</li><li><strong>Variance</strong>: The variance of the distribution is (1−p)/p2.</li><li><strong>Shape</strong>: The probability mass function (PMF) is right-skewed for p&lt;1, with the probability of success on the first trial highest.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdqFeqUAN85ib5BT3jlBCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30sIq9l259o9WnpSBJ-1Sw.png" /></figure><p><strong>Marketing Example</strong>:</p><p>Imagine a company running a marketing campaign, and the probability of a recipient opening an email is 0.2 (20%). You want to know how many emails, on average, need to be sent until you get the first response.</p><ul><li>p=0.2 (probability of success, i.e., email opened),</li><li>k is the number of trials (emails sent) until the first success (open email).</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import geom<br><br># Marketing Example (p = probability of email opened)<br>p_marketing = 0.2  # Probability of success (email opened)<br><br># Simulate the probability of first success for trials 1 through 10<br>k_values = np.arange(1, 11)  # k = 1 to 10<br>prob_success_values = geom.pmf(k_values, p_marketing)<br><br>n_trials_success = 1/p_marketing<br><br>print(f&quot;Marketing Example: how many emails  sent until you get the first response: {n_trials_success}&quot;) <br>Marketing Example: how many emails  sent until you get the first response: 5.0</pre><p><strong>Product Example</strong>:</p><p>Imagine an online platform that sells a digital product (e.g., an eBook). The probability that a potential customer buys the product after visiting the site is 0.05 (5%). You want to know how many website visits (trials) it might take until the first purchase is made.</p><ul><li>p=0.05 (probability of success, i.e., making a purchase),</li><li>k is the number of trials (website visits) until the first successful purchase.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import geom<br><br># Marketing Example (p = probability of email opened)<br>p_product = 0.05  # Probability of success (email opened)<br><br># Simulate the probability of first success for trials 1 through 10<br>k_values = np.arange(1, 11)  # k = 1 to 10<br>prob_success_values = geom.pmf(k_values, p_product)<br><br>n_trials_success = 1/p_product<br><br>print(f&quot;Product Example: how many visits until you get the first purchase: {n_trials_success}&quot;) <br>Product Example: how many visits until you get the first purchase: 20.0</pre><h4>Continuous distributions:</h4><p><strong>Exponential Distribution</strong></p><p>The <strong>Exponential Distribution</strong> describes the time between events in a Poisson process. It is often used to model waiting times, lifetimes, or time-to-failure.</p><p><strong>Key Characteristics</strong></p><ol><li><strong>Memoryless Property</strong>: The probability of an event occurring in the future is independent of how much time has already elapsed.</li><li><strong>Parameter λ\lambdaλ</strong>: Represents the rate at which events occur.</li><li><strong>Applications</strong>: Commonly used for modeling waiting times (e.g., time until the next customer arrives).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsZjL048yr2XNnwumuO4IA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vg95CEV0soKzNxTAUVD7Kg.png" /></figure><p><strong>Marketing example:</strong></p><p>A company tracks customer engagement and finds that, on average, customers remain engaged for 30 days before churning (becoming inactive). The goal is to predict the probability that a customer will churn within a certain number of days (15) and estimate the rate of churn based on observed data.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import expon<br><br># --- Time-to-Churn Example ---<br>mean_time_to_churn = 30  # Average engagement time in days<br>lambda_churn = 1 / mean_time_to_churn  # Rate of churn<br>time_threshold_churn = 15  # Time of interest (days)<br><br># Probability of churn within the threshold<br>prob_churn = expon.cdf(time_threshold_churn, scale=1/lambda_churn)<br>print(f&quot;Time-to-Churn Example: Probability a customer churns within {time_threshold_churn} days: {prob_churn:.4f}&quot;)<br># --- Plot for Time-to-Churn ---<br>x_vals_churn = np.linspace(0, 60, 100)  # Time values (e.g., 0 to 60 days)<br>pdf_churn = expon.pdf(x_vals_churn, scale=1/lambda_churn)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x_vals_churn, pdf_churn, color=&#39;blue&#39;, label=f&quot;λ={lambda_churn:.4f}&quot;)<br>plt.fill_between(x_vals_churn, pdf_churn, where=(x_vals_churn &lt;= time_threshold_churn), color=&#39;skyblue&#39;, alpha=0.5, label=f&quot;P(T ≤ {time_threshold_churn})&quot;)<br>plt.title(&quot;Exponential Distribution: Time-to-Churn&quot;)<br>plt.xlabel(&quot;Time (days)&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*4bTUKZWHP9p7jBD4XopXlQ.png" /></figure><p><strong>Product example:</strong></p><p>A website observes user interactions and finds that the average time between consecutive user sessions is 5 minutes. Using the exponential distribution, estimate the probability that the next session occurs within 2 minutes and calculate the rate of session occurrences from observed data.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import expon<br><br><br># --- Session Duration Example ---<br>mean_session_duration = 5  # Average session interval in minutes<br>lambda_session = 1 / mean_session_duration  # Rate of session occurrence<br>time_threshold_session = 2  # Time of interest (minutes)<br><br># Probability of session within the threshold<br>prob_session = expon.cdf(time_threshold_session, scale=1/lambda_session)<br>print(f&quot;Session Duration Example: Probability of next session within {time_threshold_session} minutes: {prob_session:.4f}&quot;)<br><br># --- Plot for Session Duration ---<br>x_vals_session = np.linspace(0, 15, 100)  # Time values (e.g., 0 to 15 minutes)<br>pdf_session = expon.pdf(x_vals_session, scale=1/lambda_session)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x_vals_session, pdf_session, color=&#39;green&#39;, label=f&quot;λ={lambda_session:.4f}&quot;)<br>plt.fill_between(x_vals_session, pdf_session, where=(x_vals_session &lt;= time_threshold_session), color=&#39;lightgreen&#39;, alpha=0.5, label=f&quot;P(T ≤ {time_threshold_session})&quot;)<br>plt.title(&quot;Exponential Distribution: Session Duration&quot;)<br>plt.xlabel(&quot;Time (minutes)&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*DQ53ROp1-Hx5KYYl6FZUew.png" /></figure><p><strong>Uniform Distribution</strong></p><p>The <strong>Uniform Distribution</strong> is a probability distribution where all outcomes within a specified interval are equally likely. It is characterized by two parameters: the <strong>minimum value</strong> (a) and the <strong>maximum value</strong> (b).</p><p><strong>Key Characteristics</strong></p><ol><li><strong>Constant Probability Density</strong>: All values between a and b are equally likely.</li><li><strong>Range of Values</strong>: The distribution is defined for x∈[a,b] and P(x)=0 for x&lt;a or x&gt;b.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFDYJI3-e5gKoB-_OZTqcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmgA2FAB_yMQayFK-S18cQ.png" /></figure><p><strong>Marketing Example:</strong></p><p>You estimate that customers respond to emails sent any time between 2 and 6 hours after the campaign starts. The probability of a response is equally likely within this interval. Find the probability a customer responds within the first 3 hours.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import uniform<br><br># --- Marketing Example ---<br>a_marketing = 2  # Minimum time (hours)<br>b_marketing = 6  # Maximum time (hours)<br>x_marketing = 3  # Time threshold (hours)<br><br># PDF and CDF calculations<br>prob_marketing = uniform.cdf(x_marketing, loc=a_marketing, scale=b_marketing - a_marketing)<br>print(f&quot;Marketing Example: Probability of response within {x_marketing} hours: {prob_marketing:.4f}&quot;)<br><br><br># --- Plot for Marketing Example ---<br>x_vals_marketing = np.linspace(a_marketing - 1, b_marketing + 1, 500)<br>pdf_marketing = uniform.pdf(x_vals_marketing, loc=a_marketing, scale=b_marketing - a_marketing)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x_vals_marketing, pdf_marketing, color=&#39;blue&#39;, label=f&quot;Uniform(a={a_marketing}, b={b_marketing})&quot;)<br>plt.fill_between(x_vals_marketing, pdf_marketing, where=(x_vals_marketing &lt;= x_marketing), color=&#39;skyblue&#39;, alpha=0.5, label=f&quot;P(T ≤ {x_marketing})&quot;)<br>plt.title(&quot;Uniform Distribution: Marketing Example&quot;)<br>plt.xlabel(&quot;Time (hours)&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*pideN3uSoZizixCN563OzQ.png" /></figure><p><strong>Product Example:</strong></p><p>The time it takes for a user to complete a task in a digital app is uniformly distributed between 1 and 5 minutes. Estimate the probability that a task is completed within 2 minutes.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import uniform<br><br># --- Digital Product Example ---<br>a_product = 1  # Minimum time (minutes)<br>b_product = 5  # Maximum time (minutes)<br>x_product = 2  # Time threshold (minutes)<br><br># PDF and CDF calculations<br>prob_product = uniform.cdf(x_product, loc=a_product, scale=b_product - a_product)<br>print(f&quot;Digital Product Example: Probability of task completed within {x_product} minutes: {prob_product:.4f}&quot;)<br><br><br># --- Plot for Digital Product Example ---<br>x_vals_product = np.linspace(a_product - 1, b_product + 1, 500)<br>pdf_product = uniform.pdf(x_vals_product, loc=a_product, scale=b_product - a_product)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x_vals_product, pdf_product, color=&#39;green&#39;, label=f&quot;Uniform(a={a_product}, b={b_product})&quot;)<br>plt.fill_between(x_vals_product, pdf_product, where=(x_vals_product &lt;= x_product), color=&#39;lightgreen&#39;, alpha=0.5, label=f&quot;P(T ≤ {x_product})&quot;)<br>plt.title(&quot;Uniform Distribution: Digital Product Example&quot;)<br>plt.xlabel(&quot;Time (minutes)&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*g1vODK95KXIySeB-MGOhcQ.png" /></figure><p><strong>Normal Distribution</strong></p><p>The <strong>Normal Distribution</strong>, also known as the Gaussian distribution, is a continuous probability distribution that is symmetric around its mean. It is defined by two parameters:</p><ul><li><strong>Mean</strong> (μ\muμ): The central location of the distribution.</li><li><strong>Standard Deviation</strong> (σ\sigmaσ): The measure of spread or variability.</li></ul><p>The <strong>Normal Distribution</strong> is one of the most widely used probability distributions due to its natural occurrence in real-world phenomena.</p><p>Thanks to its properties, we can calculate confidence interval with a % of confidence level, useful when you want to estimate in which range of value the true population value could fall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3KVe9P33c31HeIJLnVs3A.png" /></figure><p>Where +- Z a/2 *SE is also known as the margin of error.</p><p><strong>Key Characteristics</strong></p><ol><li><strong>Bell-shaped Curve</strong>: The probability density function is symmetric around the mean, with most of the data concentrated around it.</li><li><strong>68–95–99.7 Rule</strong>: Approximately:</li></ol><ul><li>68% of values lie within μ±σ\mu \pm \sigmaμ±σ,</li><li>95% of values lie within μ±2σ\mu \pm 2\sigmaμ±2σ,</li><li>99.7% of values lie within μ±3σ\mu \pm 3\sigmaμ±3σ.</li></ul><p><strong>3. Unbounded</strong>: Values can range from −∞ to +∞.</p><p><strong>4 .Defined by Two Parameters</strong>:</p><ul><li><strong>Mean (μ)</strong> determines the center of the distribution.</li><li><strong>Standard Deviation (σ)</strong> determines the spread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xtqp5qsx6pOc8PacrOJ3Kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voZn8KkzkpE_YTAizW7eXQ.png" /></figure><p><strong>Marketing Example:</strong></p><p>A marketing team tracks the time (in days) it takes for customers to respond to an ad. The average response time is 10 days, with a standard deviation of 2 days. What is the probability that a customer will respond within 8 days?</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import norm<br><br># --- Marketing Example ---<br>mu_marketing = 10  # Mean response time (days)<br>sigma_marketing = 2  # Standard deviation (days)<br>x_marketing = 8  # Response time threshold (days)<br><br># Calculate CDF for P(X ≤ x)<br>prob_marketing = norm.cdf(x_marketing, loc=mu_marketing, scale=sigma_marketing)<br>print(f&quot;Marketing Example: Probability of response within {x_marketing} days: {prob_marketing:.4f}&quot;)<br><br><br># --- Plot for Marketing Example ---<br>x_vals_marketing = np.linspace(mu_marketing - 4 * sigma_marketing, mu_marketing + 4 * sigma_marketing, 500)<br>pdf_marketing = norm.pdf(x_vals_marketing, loc=mu_marketing, scale=sigma_marketing)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x_vals_marketing, pdf_marketing, color=&#39;blue&#39;, label=f&quot;Normal(μ={mu_marketing}, σ={sigma_marketing})&quot;)<br>plt.fill_between(x_vals_marketing, pdf_marketing, where=(x_vals_marketing &lt;= x_marketing), color=&#39;skyblue&#39;, alpha=0.5, label=f&quot;P(X ≤ {x_marketing})&quot;)<br>plt.title(&quot;Normal Distribution: Marketing Example&quot;)<br>plt.xlabel(&quot;Response Time (days)&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*4OVaowCwzjnzDgbENzsWgA.png" /></figure><p><strong>Product Example:</strong></p><p>The time users spend on an app follows a normal distribution, with a mean session time of 30 minutes and a standard deviation of 5 minutes. What is the probability a user spends more than 35 minutes in a session?</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import norm<br><br># --- Digital Product Example ---<br>mu_product = 30  # Mean session time (minutes)<br>sigma_product = 5  # Standard deviation (minutes)<br>x_product = 35  # Session time threshold (minutes)<br><br># Calculate 1 - CDF for P(X &gt; x)<br>prob_product = 1 - norm.cdf(x_product, loc=mu_product, scale=sigma_product)<br>print(f&quot;Digital Product Example: Probability of session lasting more than {x_product} minutes: {prob_product:.4f}&quot;)<br><br># --- Plot for Digital Product Example ---<br>x_vals_product = np.linspace(mu_product - 4 * sigma_product, mu_product + 4 * sigma_product, 500)<br>pdf_product = norm.pdf(x_vals_product, loc=mu_product, scale=sigma_product)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x_vals_product, pdf_product, color=&#39;green&#39;, label=f&quot;Normal(μ={mu_product}, σ={sigma_product})&quot;)<br>plt.fill_between(x_vals_product, pdf_product, where=(x_vals_product &gt;= x_product), color=&#39;lightgreen&#39;, alpha=0.5, label=f&quot;P(X &gt; {x_product})&quot;)<br>plt.title(&quot;Normal Distribution: Digital Product Example&quot;)<br>plt.xlabel(&quot;Session Time (minutes)&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*09B8NLndU9OeBHULY4WImA.png" /></figure><p><strong>So to recap:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*UwJvsZxF92bcQwe4pRV-RA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*v96DHnAD3Tr7g-cuDpByOQ.png" /></figure><h3>5. Hypothesis Testing</h3><p>The core of inferential statistics is represented by hypothesis testing. But what is this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*cvlLm7EIjBiDW8RB.gif" /></figure><p>The hypothesis testing is a statistical method used to make inferences about populations based on sample data. The goal is to test whether there is enough evidence in the sample data to support or reject a specific hypothesis about a population parameter like the mean, proportion, etc.</p><h4>Steps in Hypothesis Testing:</h4><ol><li><strong>State the Null and Alternative Hypotheses:</strong></li></ol><ul><li><strong>Null Hypothesis (H₀)</strong>: This is the default assumption that there is no effect, no difference, or no relationship. It is typically the hypothesis that researchers try to disprove or reject.</li><li><strong>Alternative Hypothesis (H₁ or Ha)</strong>: This is the hypothesis that represents a new effect, difference, or relationship. It is what you want to prove.</li></ul><p><strong>2. Choose the Significance Level (α):</strong></p><ul><li>The <strong>alpha (α)</strong> level is the threshold for determining whether a result is statistically significant. Common values are 0.05, 0.01, or 0.10.</li></ul><p><strong>3. Select the Appropriate Test and Data:</strong></p><ul><li>Depending on the research question and the nature of the data, choose a statistical test (e.g., t-test, chi-square test, ANOVA, etc.).</li><li>Check assumptions such as the sample size, normality, or equal variances.</li></ul><p><strong>4. Compute the Test Statistic:</strong></p><ul><li>Based on the selected test, compute the test statistic (e.g., t-value, z-value, chi-square value) from the sample data.</li></ul><p><strong>5. Compute the Test Critical value</strong></p><p><strong>6. Determine the P-value:</strong></p><ul><li>The p-value is the probability of obtaining the observed data, or something more extreme, if the null hypothesis is true. Meaning, it determines if the observations are due by chance or because there is a real effect.</li><li>A small p-value (less than α) indicates strong evidence against the null hypothesis.</li></ul><p><strong>7. Make a Decision:</strong></p><ul><li>If <strong>p-value ≤ α</strong>, reject the null hypothesis. In this case, we can say the results are statistically significant.</li><li>If <strong>p-value &gt; α</strong>, fail to reject the null hypothesis. In this case, we can say the results are not statistically significant.</li><li>Depends of the test, compare test statistic and test critical value to reject or not the null hypothesis.</li></ul><p><strong>8.Draw a Conclusion:</strong></p><ul><li>Based on the decision made in the previous step, conclude whether the data supports or contradicts the null hypothesis.</li></ul><p><strong>Key elements to consider:</strong></p><p>When it comes to choosing the alpha:</p><ul><li><strong>α = 0.05</strong>: The most common threshold.</li><li><strong>α = 0.01</strong>: A more stringent threshold, used when you want to be more confident in your results.</li><li><strong>α = 0.10</strong>: A more lenient threshold, used when you’re more willing to accept the possibility of a Type I error.</li></ul><p>Errors to take into consideration:</p><p><strong>1. Type I Error (False Positive):</strong></p><ul><li>This occurs when the null hypothesis is true, but you mistakenly reject it. Essentially, you find evidence for an effect or difference that doesn’t exist.</li><li>The probability of committing a Type I error is denoted by <strong>α</strong> (alpha), which is the significance level you set for the test. In fact, setting <strong>α </strong>at the values we saw above means you are accepting the % risk of making Type I error.</li></ul><p><strong>2. Type II Error (False Negative):</strong></p><ul><li>This occurs when the null hypothesis is false, but you fail to reject it. In other words, you miss detecting an effect or difference that exists.</li><li>The probability of committing a Type II error is denoted by <strong>β</strong> (beta), and the <strong>power</strong> of a test is the probability of correctly rejecting the null hypothesis (1 — β).</li></ul><p><strong>Balancing Type I and Type II Errors:</strong></p><ul><li><strong>Reducing Type I Error</strong>: This can be done by lowering the significance level (α), but this may increase the chance of a Type II error.</li><li><strong>Reducing Type II Error</strong>: This can be achieved by increasing the sample size or using a more sensitive test, but it may increase the likelihood of a Type I error.</li></ul><p><strong>Avoid p- value hacking:</strong></p><p><strong>P-hacking</strong> refers to the manipulation or selective analysis of data to achieve a statistically significant results. This practice is often unethical and leads to misleading or false conclusions.</p><p><strong>Common Forms of P-Hacking:</strong></p><ol><li><strong>Running Multiple Tests Without Proper Adjustment</strong>:</li></ol><ul><li>A researcher may conduct several statistical tests or comparisons on the same dataset and only report the ones that yield a significant result. This increases the chances of finding a statistically significant result by chance.</li></ul><p><strong>2. Changing the Hypothesis After Seeing the Data</strong>:</p><ul><li>The researcher might adjust the hypothesis after seeing the initial results to make the data appear to support the hypothesis. This compromises the objectivity of the test.</li></ul><p><strong>3. Selective Reporting</strong>:</p><ul><li>Only reporting the results that show statistical significance and discarding the non-significant results. This gives a false impression that the data strongly supports a particular hypothesis.</li></ul><p><strong>4. Data Transformation or “Cherry-Picking”</strong>:</p><ul><li>Modifying or selecting specific data points or subsets of the data to achieve a desired outcome. This includes removing outliers or creating new variables that are more likely to yield a significant result.</li></ul><p><strong>5. Stopping Data Collection Early</strong>:</p><ul><li>A researcher may stop collecting data once a statistically significant result is found, even if the sample size is too small or the result is unlikely to be reliable.</li></ul><h3>5. 1 Significance Tests, Tables and Scores</h3><p>Significance tests are statistical procedures used to determine if the observed results are unlikely to have occurred due to chance, allowing us, poor data scientists, to infer conclusions about a population based on a sample. They rely on <strong>test statistics</strong>, <strong>critical values</strong>, and <strong>p-values</strong> to validate or refuse hypotheses.</p><p>They are divided into two main categories: parametric and non-parametric tests, differing in their assumptions, methodology, and applicability.</p><p>The term <strong>“parametric”</strong> originates from the word <strong>“parameters”</strong>, which refers to the specific numerical characteristics or constants that define a statistical model or distribution. In the context of parametric tests, the term means that these tests rely on certain <strong>parameters of the population distribution</strong> — such as the mean, variance, or standard deviation — and assume these parameters are fixed and known or can be estimated from the sample.</p><p>So the parametric tests assume the following conditions:</p><ul><li><strong>Normality</strong>: The data is assumed to be normally distributed (or at least approximately normal).</li><li><strong>Homogeneity of Variance</strong>: Variances within each group being compared should be equal.</li><li><strong>Interval/Ratio Data</strong>: The data being analyzed is continuous and measured on an interval or ratio scale.</li><li><strong>Independent observations</strong>: Observations should be independent of each other.</li></ul><p>While the non-parametric tests:</p><ul><li><strong>No normality assumption</strong>: There is no requirement for the data to follow a normal distribution.</li><li><strong>Ordinal/Rank Data</strong>: The data may be ordinal (ranked) or continuous but skewed.</li><li><strong>Independent observations</strong>: Observations should still be independent.</li></ul><p>When deciding which statistical test to use, it’s important to consider the following assumptions:</p><ol><li><strong>Sample Size</strong>:</li></ol><ul><li>Parametric tests generally require larger sample sizes to meet their assumptions (e.g., normality).</li><li>Non-parametric tests can be used effectively with smaller sample sizes and with data that does not meet parametric assumptions.</li></ul><p><strong>2. Normality of Data</strong>:</p><ul><li><strong>Parametric tests</strong> assume that the data follows a normal distribution.</li><li><strong>Non-parametric tests</strong> make no assumptions about the distribution and are useful when the data is skewed or not normally distributed.</li><li>You can test for normality using graphical methods (like histograms or Q-Q plots) or statistical tests (e.g., Shapiro-Wilk test).</li></ul><p><strong>3. Type of Data</strong>:</p><ul><li><strong>Parametric tests</strong> are suitable for continuous (interval or ratio) data.</li><li><strong>Non-parametric tests</strong> are more appropriate for ordinal (ranked) data or categorical data.</li><li>For example, the Chi-square tests for categorical data and Mann-Whitney U test for ordinal data.</li></ul><p><strong>4. Homogeneity of Variance (for tests comparing groups)</strong>:</p><ul><li>Some parametric tests like t-tests and ANOVA assume that the variances within groups are approximately equal. If this assumption is violated, you may consider using a non-parametric alternative like Kruskal-Wallis test.</li></ul><p><strong>5. Independence of Observations</strong>:</p><ul><li>Most tests assume that the observations are independent of each other. If the observations are paired or dependent (such as before-and-after measurements on the same subjects), paired versions of parametric or non-parametric tests should be used.</li></ul><p><strong>6. Nature of the Research Question</strong>:</p><ul><li>If you’re comparing two groups (e.g., comparing means between two conditions), you might choose a t-test or its non-parametric counterpart, the Mann-Whitney U test.</li><li>If you’re comparing more than two groups, ANOVA or its non-parametric equivalent, the Kruskal-Wallis test, may be more appropriate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rchV95vTk7HKo62lI4DRRQ.png" /></figure><p>For the big picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*l5mV5O_hRDdvxUQ18RHBYQ.png" /><figcaption>Source:<a href="https://medium.com/geekculture/statistical-test-cheat-sheet-73cf0770c8f6">https://medium.com/geekculture/statistical-test-cheat-sheet-73cf0770c8f6</a></figcaption></figure><p>In this blog post, we will investigate only:</p><p><strong>Parametric tests:</strong></p><ul><li>t-Test</li><li>Z-Test</li><li>ANOVA</li><li>Pearson Correlation Coefficient</li></ul><p><strong>Non-Parametric Tests:</strong></p><ul><li>Chi-Square Test</li><li>Mann-Whitney U Test (Wilcoxon Signed-Rank Test)</li><li>Kruskal-Wallis Test</li><li>Spearman Rank Correlation</li></ul><h4><strong>T-Test</strong></h4><p>The t-test is a statistical method to test whether there is a significant difference between the means of one or two groups. It is most commonly used when dealing with small sample sizes and continuous data, assuming normality, equality of variances and the population standard deviation is unknown.</p><p><strong>Assumptions to be met</strong></p><ol><li><strong>Normality</strong>:</li></ol><ul><li>Data in each group should follow a normal distribution.</li><li>Check using tests like Shapiro-Wilk or visual methods (histograms, Q-Q plots).</li><li>Works well for small-to-medium samples (n&lt; 30); large samples rely on the Central Limit Theorem.</li></ul><p><strong>2. Independence</strong>:</p><ul><li>Observations must be independent within and between groups.</li><li>Ensure no overlapping data or dependencies in measurement processes.</li></ul><p><strong>3. Equal Variance</strong>:</p><ul><li>Variances in both groups should be similar for the Independent t-Test.</li></ul><p><strong>4. Scale</strong>:</p><ul><li>The dependent variable must be measured on an interval or ratio scale (e.g., revenue, weight, time).</li></ul><p>In case the assumptions are not met, the alternatives are:</p><ul><li><strong>One-Sample t-Test</strong> → <strong>One-Sample Wilcoxon Signed Rank Test</strong>.</li><li><strong>Independent t-Test</strong> → <strong>Mann-Whitney U Test</strong>.</li><li><strong>Paired t-Test</strong> → <strong>Wilcoxon Signed Rank Test</strong>.</li></ul><p><strong>When to Use a T-test:</strong></p><p><strong>Type of Data:</strong></p><ul><li>Continuous dependent variable (e.g., revenue, temperature).</li></ul><p><strong>Sample Size:</strong></p><ul><li>Small to medium-sized samples (typically n&lt; 30 per group). For large samples, alternative methods (e.g., z-tests) may be more appropriate.</li></ul><p><strong>Situations:</strong></p><ul><li>Compare one group mean to a population mean (One-Sample t-Test).</li><li>Compare means of two independent groups (Independent t-Test).</li><li>Compare the means of two related groups (Paired t-Test).</li></ul><p><strong>The goal of the t-test is to compare the t-statistic to the critical value to reject or not the null hypothesis. The p-value will ensure the strength of the rejection or not.</strong></p><p>In detail:</p><p>The <strong>t-statistic</strong> quantifies how many standard errors the observed difference is away from the null hypothesis value.</p><p><strong>One-Sample t-test</strong>:</p><p>Compares the sample mean (x̄) to a known or hypothesized population mean (μ0).</p><p>t = (x̄ — μ) / (s / √n)</p><p>Where:</p><ul><li>x̄ is the sample mean</li><li>μ is the hypothesized population mean</li><li>s is the sample standard deviation</li><li>n is the sample size</li></ul><p><strong>Independent t-test</strong> (Two-Sample t-Test):</p><p>Compares the means of two independent groups.</p><p>t = (x̄₁ — x̄₂) / √(s₁²/n₁ + s₂²/n₂)</p><p>Where:</p><ul><li>x̄₁ and x̄₂ are the sample means of the two groups</li><li>s₁ and s₂ are the sample standard deviations of the two groups</li><li>n₁ and n₂ are the sample sizes of the two groups</li></ul><p><strong>Paired t-Test</strong>:</p><p>Compares the means of two related groups (e.g., pre-test and post-test).</p><p>t = d̄ / (sd/ √n)</p><p>Where:</p><ul><li>d̄ is the mean of the differences between paired observations</li><li>sd is the standard deviation of the differences</li><li>n is the number of pairs</li></ul><p>Once you have the t-statistic you need the critical value.</p><p>The critical t-value is the threshold value used to determine whether to reject the null hypothesis. It is based on:</p><ol><li>Degrees of Freedom (df): Number of independent observations minus the parameters estimated:</li></ol><ul><li>One-Sample and Paired t-Test: df=n−1</li><li>Independent t-Test: df=n1+n2−2</li></ul><p>2. Significance Level (α): Commonly 0.05 for a 95% confidence level.</p><p>It can be extracted using the t-table or using Python:</p><pre>from scipy.stats import t<br><br># Parameters<br>df = 10  # Degrees of freedom<br>alpha = 0.05  # Significance level<br><br># Critical value for a two-tailed test<br>t_critical = t.ppf(1 - alpha / 2, df)<br>print(f&quot;Critical t-value (two-tailed): ±{t_critical:.3f}&quot;)<br># Critical value for a one-tailed test<br>t_critical_one_tailed = t.ppf(1 - alpha, df)<br>print(f&quot;Critical t-value (one-tailed): {t_critical_one_tailed:.3f}&quot;)</pre><p>The distribution used in this test is called t-distribution. It is used to model the distribution of the t-statistic under the null hypothesis:</p><ul><li>Symmetric and bell-shaped with heavier tails than a normal distribution.</li><li>The shape depends on df; larger df approaches normality.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*6v0UosfHdOeA9musCF2Xhg.png" /></figure><p>For the H0 to be rejected, the statistic has to fall into the rejection area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*aP8nC6tkXprk0irUQU-H-g.png" /></figure><p>and being greater or lower than the critical value, depending on the test.</p><p>The p-value is the probability of observing the test statistic as extreme as the one computed, assuming H0​ is true.</p><ul><li>p&lt;α: Reject H0​ (significant difference).</li><li>p≥α: Fail to reject H0(no significant difference).</li></ul><p><strong>Marketing example:</strong></p><p>Imagine a company launched a new marketing campaign and wants to check if the average sales during the campaign period are significantly different from their usual average sales (the historical average). The historical average sales for the past several months is $10,000 per week. The company tracked sales during the first 10 weeks of the new marketing campaign and wants to test if the average sales have increased.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy import stats<br><br># Simulated sales data during the marketing campaign (in dollars)<br>sales_data = np.array([11500, 12000, 11000, 12500, 13000, 13500, 14000, 12500, 11800, 12400])<br><br># Historical average sales (population mean) of $10,000 per week<br>historical_average_sales = 10000<br><br># Perform one-sample t-test<br>t_stat, p_value = stats.ttest_1samp(sales_data, historical_average_sales)<br><br># Degrees of freedom<br>df = len(sales_data) - 1<br><br># Critical value for a two-tailed test at alpha = 0.05<br>alpha = 0.05<br>critical_value = stats.t.ppf(1 - alpha/2, df)  # For two-tailed test<br><br># Output the result<br>print(f&quot;T-statistic: {t_stat}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br>print(f&quot;Degrees of Freedom: {df}&quot;)<br>print(f&quot;Critical Value (α = 0.05): {critical_value}&quot;)<br><br># Plotting the T-distribution and highlighting the T-statistic<br>x = np.linspace(-4, 4, 1000)<br>y = stats.t.pdf(x, df)<br><br>plt.figure(figsize=(8, 6))<br>plt.plot(x, y, label=&quot;T-distribution&quot;, color=&quot;blue&quot;)<br>plt.fill_between(x, y, where=(x &gt;= critical_value), color=&quot;red&quot;, alpha=0.5, label=&quot;Critical Region (Right Tail)&quot;)<br>plt.fill_between(x, y, where=(x &lt;= -critical_value), color=&quot;red&quot;, alpha=0.5, label=&quot;Critical Region (Left Tail)&quot;)<br><br># Highlight the T-statistic<br>plt.axvline(x=t_stat, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=f&quot;T-statistic: {t_stat:.2f}&quot;)<br><br># Labels and title<br>plt.title(&quot;T-Distribution with Highlighted T-Statistic and Critical Region&quot;)<br>plt.xlabel(&quot;T-value&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend(loc=&quot;best&quot;)<br>plt.grid(True)<br><br># Show the plot<br>plt.show()<br><br># Interpretation based on the T-statistic and critical value<br>if abs(t_stat) &gt; critical_value:<br>    print(&quot;Reject the null hypothesis: The average sales during the campaign are significantly different from the historical average.&quot;)<br>else:<br>    print(&quot;Fail to reject the null hypothesis: The average sales during the campaign are not significantly different from the historical average.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*xBRxFJ0-d7y9SA7Yiyq-mQ.png" /></figure><h4><strong>Z-Test</strong></h4><p>The z-test is a statistical method to test whether there is a significant difference between the means of the sample and the population mean or between two independent groups. It is most commonly used when dealing with large sample sizes, and the population standard deviation is known.</p><p><strong>Assumptions of Z-Test</strong></p><ol><li><strong>Normality</strong>:</li></ol><ul><li>The data is normally distributed, OR the sample size is sufficiently large (n≥30), so the Central Limit Theorem ensures approximate normality.</li></ul><p><strong>2. Known Population Variance</strong>:</p><ul><li>The population variance (σ2) or standard deviation (σ) is known.</li></ul><p><strong>3. Random Sampling</strong>:</p><ul><li>The sample(s) must be drawn randomly from the population.</li></ul><p><strong>4. Independence</strong>:</p><ul><li>Observations within the sample, and between samples (for two-sample tests), must be independent.</li></ul><p>When the assumptions are violated use:</p><p>In case the assumptions are not met, the alternatives are:</p><ul><li><strong>One-Sample z-Test</strong> → <strong>Wilcoxon Signed Rank Test (Mann-Whitney U Test)</strong>.</li><li><strong>Two-Samples z-Test</strong> → <strong>Wilcoxon Signed Rank Test (Mann-Whitney U Test)</strong>.</li></ul><p>When using a z-test:</p><ul><li><strong>One-Sample Z-Test</strong>: When comparing the mean of a single sample to a known population mean.</li><li><strong>Two-Sample Z-Test</strong>: When comparing the means of two independent samples.</li><li><strong>Z-Test for Proportions</strong>: When comparing proportions (e.g., percentages).</li></ul><p><strong>The goal of the z-test is to compare the z-statistic to the critical value to reject or not the null hypothesis. The p-value will ensure the strength of the rejection or not.</strong></p><p>In detail:</p><p>The <strong>z-statistic (z-score) </strong>quantifies how far the sample mean (or difference between sample means) is from the hypothesized population mean (or difference between population means) in terms of standard errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*PD4EDioB-3cwjGGZ.gif" /></figure><p>Before we continue on the z-score the types of the z-test, we have to focus on the z-score in general and why it is so important.</p><p>The use of z-score goes behind its application in hypothesis testing.</p><p>In general, the z-score quantifies how many standard deviations the data point is from the mean of its distribution. It is used to standardize data from different distributions, allowing for meaningful comparisons. It transforms raw data into a common scale with a mean of 0 and a standard deviation of 1.</p><p>Formula:</p><p>z = (x — μ) / σ</p><p>Where:</p><p>x: The individual data point</p><p>μ: The population mean</p><p>σ: The population standard deviation</p><p>For further explanation, watch this <a href="https://www.youtube.com/watch?v=kPjK2SmUPNc">video</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*PD4EDioB-3cwjGGZ.gif" /></figure><p><strong>One-Sample Z-test</strong></p><p>This test compares the mean of a single sample to a known population mean.</p><p>z = (x̄ — μ) / (σ / √n)</p><p>Where:</p><p>x̄: The sample mean</p><p>μ: The population mean</p><p>σ: The population standard deviation</p><p>n: The sample size</p><p>The term (σ / √n) is known as the standard error of the mean. It represents the standard deviation of the sampling distribution of the mean.</p><p><strong>Two-Sample Z-test</strong></p><p>This test compares the means of two independent samples.</p><p>z = (x̄₁ — x̄₂) / √(σ₁²/n₁ + σ₂²/n₂)</p><p>Where:</p><p>x̄₁: The mean of the first sample</p><p>x̄₂: The mean of the second sample</p><p>σ₁: The population standard deviation of the first population</p><p>σ₂: The population standard deviation of the second population</p><p>n₁: The size of the first sample</p><p>n₂: The size of the second sample</p><p><strong>Z-Test for proportions</strong></p><p>This test determines if a sample proportion is significantly different from a hypothesized population proportion.</p><p>z = (p̂ — p₀) / √(p₀(1 — p₀) / n)</p><p>Where:</p><p>p̂: The sample proportion (number of successes in the sample / total sample size)</p><p>p₀: The hypothesized population proportion (the value you’re testing against in the null hypothesis)</p><p>n: The sample size</p><p>Once you have the z-score, to reject or not the null hypothesis, you need to find the z critical value.</p><p>This can be found using the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*HZCM10_NywHFrVXxqd78QA.png" /><figcaption><a href="https://www.craftonhills.edu/current-students/tutoring-center/mathematics-tutoring/distribution_tables_normal_studentt_chisquared.pdf">https://www.craftonhills.edu/current-students/tutoring-center/mathematics-tutoring/distribution_tables_normal_studentt_chisquared.pdf</a></figcaption></figure><p>Where:</p><ul><li>row = z-score</li><li>column = second decimal digit</li><li>value = cumulative area under the curve</li></ul><p>or using python:</p><pre>import scipy.stats as stats<br><br># Given confidence level (1 - alpha) for a two-tailed test<br>confidence_level = 0.95  # Example: 95% confidence level<br>alpha = 1 - confidence_level  # Calculate alpha<br><br># For a two-tailed test<br>z_critical_two_tailed = stats.norm.ppf(1 - alpha/2)<br><br># For a one-tailed test<br>z_critical_one_tailed = stats.norm.ppf(1 - alpha)<br><br># Display the results<br>print(f&quot;Z-Critical Value (Two-Tailed, {confidence_level*100}% confidence): {z_critical_two_tailed:.4f}&quot;)<br>print(f&quot;Z-Critical Value (One-Tailed, {confidence_level*100}% confidence): {z_critical_one_tailed:.4f}&quot;)<br>Z-Critical Value (Two-Tailed, 95.0% confidence): 1.9600<br>Z-Critical Value (One-Tailed, 95.0% confidence): 1.6449</pre><p>The distribution used in this test is called the Standard Normal Distribution. It is used to model the distribution of the z-statistic under the null hypothesis. Why standard? Because this particular distribution is “standardized” and it has a mean = 0 and a standard deviation = 1.</p><p>Determining if rejecting the null hypothesis depends on the “direction of the test”</p><ul><li>two-tailed = H0 != H1 meaning the z-score has to exceed the critical value in both directions +-</li><li>one-tailed = H0 greater than H1 or vice-versa meaning the z-score has to be greater or lower than the critical value in the direction selected.</li></ul><p>Once you have found the critical value, you will find the p-value:</p><p>The p-value is the probability of observing the test statistic as extreme as the one computed, assuming H0​ is true.</p><ul><li>p&lt;α: Reject H0​ (significant difference).</li><li>p≥α: Fail to reject H0(no significant difference).</li></ul><p><strong>Marketing example:</strong></p><p>You are a marketing analyst tasked with evaluating the effectiveness of two different customer segments in terms of their spending behaviour. Segment A and Segment B represent two groups of users targeted by distinct marketing campaigns. To determine whether the average spend per user differs significantly between these two groups, you decide to perform a Z-test to compare their means.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from statsmodels.stats.weightstats import ztest<br>from scipy.stats import norm<br><br># Simulated data for two user segments<br># Segment A<br>mean_a = 50.5  # Average spend for Segment A<br>std_a = 10.2   # Standard deviation for Segment A<br>n_a = 500      # Sample size for Segment A<br><br># Segment B<br>mean_b = 48.2  # Average spend for Segment B<br>std_b = 9.8    # Standard deviation for Segment B<br>n_b = 450      # Sample size for Segment B<br><br># Generate random samples for simulation<br>np.random.seed(42)<br>data_a = np.random.normal(mean_a, std_a, n_a)<br>data_b = np.random.normal(mean_b, std_b, n_b)<br><br># Perform the Z-test<br>z_stat, p_value = ztest(data_a, data_b, alternative=&#39;two-sided&#39;)<br><br># Calculate the critical value for a two-sided test<br>alpha = 0.05<br>critical_value = norm.ppf(1 - alpha / 2)  # Two-sided critical value<br><br># Print results<br>print(&quot;Z-Statistic:&quot;, z_stat)<br>print(&quot;P-Value:&quot;, p_value)<br>print(&quot;Critical Value (two-sided, alpha = 0.05): ±&quot;, critical_value)<br><br># Plot the standard normal distribution<br>x = np.linspace(-4, 4, 1000)<br>y = norm.pdf(x, 0, 1)  # Standard normal distribution<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x, y, label=&#39;Standard Normal Distribution&#39;, color=&#39;black&#39;)<br><br># Shade the rejection regions<br>plt.fill_between(x, y, where=(x &lt;= -critical_value) | (x &gt;= critical_value), color=&#39;red&#39;, alpha=0.3, label=&#39;Rejection Region (α = 0.05)&#39;)<br><br># Plot the Z-score<br>plt.axvline(z_stat, color=&#39;blue&#39;, linestyle=&#39;--&#39;, linewidth=2, label=f&quot;Z-Score = {z_stat:.2f}&quot;)<br><br># Add text for critical values<br>plt.axvline(-critical_value, color=&#39;red&#39;, linestyle=&#39;--&#39;, linewidth=1)<br>plt.axvline(critical_value, color=&#39;red&#39;, linestyle=&#39;--&#39;, linewidth=1)<br>plt.text(-critical_value - 0.4, 0.02, f&quot;-{critical_value:.2f}&quot;, color=&#39;red&#39;, fontsize=12)<br>plt.text(critical_value + 0.1, 0.02, f&quot;{critical_value:.2f}&quot;, color=&#39;red&#39;, fontsize=12)<br><br># Plot configuration<br>plt.title(&#39;Z-Test Visualization: Standard Normal Distribution&#39;, fontsize=16)<br>plt.xlabel(&#39;Z-Score&#39;, fontsize=14)<br>plt.ylabel(&#39;Density&#39;, fontsize=14)<br>plt.legend(fontsize=12)<br>plt.grid(alpha=0.3)<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()<br><br># Interpret the result<br>if abs(z_stat) &gt; critical_value:<br>    print(&quot;Reject the null hypothesis: The means of the two segments are significantly different.&quot;)<br>else:<br>    print(&quot;Fail to reject the null hypothesis: No significant difference between the means of the two segments.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*nS7Fk4g3JaBymXaAZTruyA.png" /></figure><h4><strong>ANOVA Test</strong></h4><p>The ANOVA (Analysis of Variance) is a statistical test used to determine whether there are significant differences between the means of <strong>three or more independent groups</strong>. It evaluates whether observed differences in sample means are due to actual differences or random chance. This type of analysis helps us to understand if the variation in one factor (independent variable) leads to a difference in the dependent variable. ANOVA works by analyzing the variance in the data and partitioning it into variance between groups and the variance within groups.</p><p><strong>Assumptions of ANOVA</strong></p><ol><li><strong>Independence</strong>: Observations are independent of one another.</li><li><strong>Normality</strong>: The dependent variable is approximately normally distributed within each group.</li><li><strong>Homogeneity of Variance</strong>: Variances across groups are equal (can be tested using Levene’s test).</li><li><strong>Continuous Dependent Variable</strong>: The variable being measured (e.g., revenue, scores) should be continuous.</li></ol><p><strong>When to Use ANOVA</strong></p><ul><li>Comparing the means of three or more groups or categories.</li><li>When the dependent variable is continuous (e.g., sales, time, click-through rate).</li><li>When the independent variable(s) are categorical (e.g., product categories, ad campaigns).</li><li>Examples:</li><li>Testing the effectiveness of different marketing campaigns.</li><li>Analyzing sales performance across regions.</li></ul><p><strong>Non-Parametric Alternatives to ANOVA</strong></p><p>If the assumptions of ANOVA are violated, you can use:</p><ol><li><strong>Kruskal-Wallis Test</strong>: Non-parametric alternative for one-way ANOVA.</li><li><strong>Friedman Test</strong>: Non-parametric alternative for repeated-measures ANOVA.</li></ol><p><strong>The goal of ANOVA is to assess whether the differences in means between the groups are statistically significant. In this case, the statistic calculated is the F-statistic, which compares the variance between groups to the variance within groups.</strong></p><h4>One-Way ANOVA</h4><p>In one-way ANOVA, you compare the means of three or more groups. Here’s how you compute the F-statistic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9HU6FW-kPboO5HZ9xLlEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44DMkUR5yRAQ-datKjGUVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V36sDtg_LM68X9BNoyp_xA.png" /></figure><p>and finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gzh7kZXZxsl1IKv6dVqb7w.png" /></figure><h4>Two-Way ANOVA</h4><p>In a two-way ANOVA, you analyze the effect of two independent variables (factors) on a dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yIrvROYxH16DLzqe8aCnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6CkO7S8g8KQEkribuZIAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNEIm2-nGM9z7Nzp6SK07g.png" /></figure><h4>Repeated Measures ANOVA</h4><p>This is used when the same subjects are measured under different conditions.</p><p>The F-statistic here is similar but accounts for the <strong>within-subject variability</strong>.</p><ul><li><strong>Sum of Squares Between Conditions (SSB)</strong>: Measures differences between different conditions.</li><li><strong>Sum of Squares Within (SSW)</strong>: Measures variability within subjects after adjusting for the between-condition effects.</li><li><strong>Degrees of Freedom</strong>: Similar to one-way ANOVA but adjusted for repeated measurements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeqgjwoaK89tnIcoqQmbOQ.png" /></figure><p>So the<strong> F-statistic</strong> is a ratio of variance between groups to the variance within groups. It tells you whether the means of the groups are statistically significantly different. A higher<strong> F-value</strong> means a greater likelihood of rejecting the null hypothesis (i.e., there is a significant difference between the groups).</p><p>or you can use python:</p><pre>import pandas as pd<br>import statsmodels.formula.api as smf  # For formulas<br>import statsmodels.api as sm          # For the stats module<br>from statsmodels.stats.anova import AnovaRM  # For Repeated Measures ANOVA<br>import scipy.stats as stats<br><br># --- One-Way ANOVA Data ---<br>one_way_data = {&#39;Value&#39;: [10, 12, 14, 11, 13, 15, 9, 11, 12],<br>                &#39;Group&#39;: [&#39;A&#39;, &#39;A&#39;, &#39;A&#39;, &#39;B&#39;, &#39;B&#39;, &#39;B&#39;, &#39;C&#39;, &#39;C&#39;, &#39;C&#39;]}<br>df_one_way = pd.DataFrame(one_way_data)<br><br># --- Two-Way ANOVA Data ---<br>two_way_data = {&#39;Value&#39;: [20, 22, 25, 23, 26, 28, 18, 20, 22, 19, 21, 23],<br>                &#39;Factor1&#39;: [&#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;Y&#39;, &#39;Y&#39;, &#39;Y&#39;, &#39;Y&#39;, &#39;Y&#39;, &#39;Y&#39;],<br>                &#39;Factor2&#39;: [&#39;P&#39;, &#39;Q&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;P&#39;, &#39;Q&#39;]}<br><br>df_two_way = pd.DataFrame(two_way_data)<br><br># --- Repeated Measures ANOVA Data ---<br>repeated_data = {&#39;Subject&#39;: [1, 1, 1, 2, 2, 2, 3, 3, 3],<br>                 &#39;Time&#39;: [&#39;Pre&#39;, &#39;Mid&#39;, &#39;Post&#39;, &#39;Pre&#39;, &#39;Mid&#39;, &#39;Post&#39;, &#39;Pre&#39;, &#39;Mid&#39;, &#39;Post&#39;],<br>                 &#39;Score&#39;: [10, 12, 15, 8, 9, 11, 11, 13, 14]}<br>df_repeated = pd.DataFrame(repeated_data)<br><br># --- Perform ANOVAs ---<br><br># 1. One-Way ANOVA<br>f_statistic, p_value = stats.f_oneway(df_one_way[&#39;Value&#39;][df_one_way[&#39;Group&#39;] == &#39;A&#39;],<br>                                      df_one_way[&#39;Value&#39;][df_one_way[&#39;Group&#39;] == &#39;B&#39;],<br>                                      df_one_way[&#39;Value&#39;][df_one_way[&#39;Group&#39;] == &#39;C&#39;])<br>print(&quot;\nOne-Way ANOVA:&quot;)<br>print(&quot;F-statistic:&quot;, f_statistic)<br>print(&quot;P-value:&quot;, p_value)<br><br># 2. Two-Way ANOVA<br>model_two_way = smf.ols(&#39;Value ~ C(Factor1) + C(Factor2) + C(Factor1):C(Factor2)&#39;, data=df_two_way).fit()<br>anova_table_two_way = sm.stats.anova_lm(model_two_way, typ=2)<br>print(&quot;\nTwo-Way ANOVA:&quot;)<br>print(anova_table_two_way)<br><br># 3. Repeated Measures ANOVA (Corrected)<br>rm_anova = AnovaRM(data=df_repeated, depvar=&#39;Score&#39;, subject=&#39;Subject&#39;, within=[&#39;Time&#39;])<br>results_repeated = rm_anova.fit()<br>print(&quot;\nRepeated Measures ANOVA:&quot;)<br>print(results_repeated)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*yS2g-DIpgwXXk-TfbbeCLA.png" /></figure><p>Once you have the F-statistic, you need to find the critical value, as for the other test, to help you reject or not the null hypothesis. If the F-statistic is greater than the critical value from the F-table, you reject the null hypothesis. In this case, we use the F-Table that depends on two dfs (degree of freedom) for a given significance level (α). :</p><ul><li>df1 (numerator, degrees of freedom between groups) = k-1 (where k is the number of groups)</li><li>df2 (denominator, degrees of freedom within groups) = N-k (where N is the total number of observations and k is the number of the groups)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*mw-svnNLKKSTO5JMphfCVA.png" /><figcaption><a href="https://www.stat.purdue.edu/~lfindsen/stat503/F_alpha_05.pdf">https://www.stat.purdue.edu/~lfindsen/stat503/F_alpha_05.pdf</a></figcaption></figure><p>or using this <a href="https://datatab.net/tutorial/f-distribution">website</a> or using python:</p><pre>import scipy.stats as stats<br><br># Define parameters for the F-distribution<br>df1 = 2  # Degrees of freedom between groups (numerator)<br>df2 = 10  # Degrees of freedom within groups (denominator)<br>alpha = 0.05  # Significance level (commonly used value)<br><br># Find the critical value from the F-distribution<br>f_critical = stats.f.ppf(1 - alpha, df1, df2)<br><br>print(f&quot;The critical F-value for alpha = {alpha}, df1 = {df1}, df2 = {df2} is: {f_critical:.4f}&quot;)<br>The critical F-value for alpha = 0.05, df1 = 2, df2 = 10 is: 4.1028</pre><p>In this case, in order to reject tu null hypothesis the f-statistic has to be greater than the critical value since the critical value is always positive and the f-distribution, the distribution for this test, is right skewed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*T892KSmiOyN8_kdXRkSQ1g.png" /></figure><p>The p-value represents the probability of observing the data if the null hypothesis (H0​: all group means are equal) is true.</p><p><strong>Decision Rule</strong>:</p><ul><li>p-value &lt;α (e.g., 0.05): Reject H0​. At least one group mean is significantly different.</li><li>p-value ≥α: Fail to reject H0​.</li></ul><p><strong>Marketing example:</strong></p><p>You are analyzing the effectiveness of different <strong>ad copy strategies</strong> for a digital product. Your goal is to understand if the <strong>average conversion rate</strong> (the percentage of visitors who make a purchase) differs significantly between three different <strong>ad copy types</strong>.</p><p>You have data for the conversion rates of visitors exposed to three different types of ad copies for your digital product, and you want to use <strong>One-Way ANOVA</strong> to test if there is a significant difference in the average conversion rate between the ad copies.</p><p><strong>Hypothesis:</strong></p><ul><li><strong>Null Hypothesis (H₀)</strong>: There is no significant difference in the conversion rates between the three ad copies.</li><li><strong>Alternative Hypothesis (H₁)</strong>: There is a significant difference in the conversion rates between the three ad copies.</li></ul><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br># Simulated conversion rates for each ad copy (3 ad copies with 100 visitors each)<br>ad_copy_a = np.random.normal(loc=3.5, scale=1.5, size=100)  # Ad Copy A: mean 3.5% conversion rate<br>ad_copy_b = np.random.normal(loc=3.8, scale=1.5, size=100)  # Ad Copy B: mean 3.8% conversion rate<br>ad_copy_c = np.random.normal(loc=3.7, scale=1.5, size=100)  # Ad Copy C: mean 3.7% conversion rate<br><br># Perform One-Way ANOVA<br>f_statistic, p_value = stats.f_oneway(ad_copy_a, ad_copy_b, ad_copy_c)<br><br># Output the F-statistic and p-value<br>print(f&quot;F-statistic: {f_statistic}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br><br># Interpretation<br>if p_value &lt; 0.05:<br>    print(&quot;Reject the null hypothesis: There is a significant difference in conversion rates between the ad copies.&quot;)<br>else:<br>    print(&quot;Fail to reject the null hypothesis: There is no significant difference in conversion rates between the ad copies.&quot;)<br><br># --- Visualizing the results ---<br><br># Boxplot for the conversion rates by ad copy<br>plt.figure(figsize=(8, 5))<br>plt.boxplot([ad_copy_a, ad_copy_b, ad_copy_c], labels=[&#39;Ad Copy A&#39;, &#39;Ad Copy B&#39;, &#39;Ad Copy C&#39;])<br>plt.title(&#39;Conversion Rates by Ad Copy&#39;)<br>plt.ylabel(&#39;Conversion Rate (%)&#39;)<br>plt.show()<br><br># --- F-distribution Visualization ---<br><br># Degrees of freedom for the F-distribution (between-group df = 2, within-group df = 297)<br>df1 = 2  # Between-group degrees of freedom (k - 1), where k is the number of groups (3 ad copies)<br>df2 = 297  # Within-group degrees of freedom (n - k), where n is the total sample size (300 samples)<br><br># Critical F-value for the rejection region (right tail, alpha = 0.05)<br>alpha = 0.05<br>f_critical = stats.f.ppf(1 - alpha, df1, df2)<br><br># Create an array of F-values for plotting the entire distribution<br>x = np.linspace(0, 5, 1000)  # F-values from 0 to 5 (covering most of the distribution)<br>y = stats.f.pdf(x, df1, df2)  # Probability density function for the F-distribution<br><br># Plot the entire F-distribution curve<br>plt.figure(figsize=(10, 6))<br>plt.plot(x, y, label=f&#39;F-distribution (df1={df1}, df2={df2})&#39;, color=&#39;blue&#39;)<br><br># Shade the rejection area (right tail) beyond the critical F-value<br>x_fill = np.linspace(f_critical, 5, 1000)<br>y_fill = stats.f.pdf(x_fill, df1, df2)<br>plt.fill_between(x_fill, y_fill, color=&#39;red&#39;, alpha=0.5, label=f&#39;Rejection area (Critical F &gt; {f_critical:.2f})&#39;)<br><br># Add a vertical line for the critical F-value<br>plt.axvline(f_critical, color=&#39;black&#39;, linestyle=&#39;dashed&#39;, label=f&#39;Critical F-value = {f_critical:.2f}&#39;)<br><br># Highlight the area where the F-statistic lies (green vertical line)<br>plt.axvline(f_statistic, color=&#39;green&#39;, linestyle=&#39;solid&#39;, label=f&#39;F-statistic = {f_statistic:.2f}&#39;)<br><br># Labels and title for the F-distribution plot<br>plt.title(f&#39;F-distribution with Entire Curve and Rejection Area (df1={df1}, df2={df2})&#39;)<br>plt.xlabel(&#39;F-value&#39;)<br>plt.ylabel(&#39;Density&#39;)<br><br># Show the plot with a legend<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*2EFSPTPLmSPP4gjWoCFw6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*o5S3QxF52-aVrz7Zxm43Yw.png" /></figure><h4><strong>Pearson Correlation “Test”</strong></h4><p>The <strong>Pearson Correlation Coefficient (r)</strong> quantifies the strength and direction of the linear relationship between two continuous variables. In hypothesis testing, we determine if the observed correlation is statistically significant.</p><p><strong>Assumptions to be met</strong>:</p><ul><li>Both variables are continuous and normally distributed.</li><li>The relationship between variables is linear.</li><li>No significant outliers.</li><li>Observations are independent.</li></ul><p>In case the assumptions are violated, we can use <strong>Spearman Rank Correlation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ej03U_fPsm5HZ4fEfXRFA.png" /></figure><p>Where:</p><ul><li>r: Observed Pearson correlation coefficient.</li><li>n: Number of data points (sample size).</li><li>Degrees of freedom (df) = n−2 (for two-tailed test)</li></ul><p><strong>Key Considerations</strong></p><ol><li><strong>Direction</strong>: r&gt;0 indicates a positive linear relationship and r&lt;0 indicates a negative one.</li><li><strong>Strength</strong>:</li></ol><ul><li>∣r∣≈0.1|r| \approx 0.1∣r∣≈0.1: Weak.</li><li>∣r∣≈0.3|r| \approx 0.3∣r∣≈0.3: Moderate.</li><li>∣r∣≈0.5|r| \approx 0.5∣r∣≈0.5 or higher: Strong.</li></ul><p><strong>3. Significance</strong>: A statistically significant r doesn’t imply a causative relationship, only that one exists.</p><p>The steps are equal to the other significance tests.</p><ol><li>Formulate the hypothesis:</li></ol><p>In this case, our hypothesis will be:</p><ul><li><strong>Null Hypothesis (H0)</strong>: There is no linear relationship between the two variables (r=0).</li><li><strong>Alternative Hypothesis (Ha​)</strong>: There is a linear relationship between the two variables (r≠0).</li></ul><p>2. Compute the t-statistic</p><p>3. Compute the t-critical value from the <strong>t-distribution</strong> table, the r-critical value and its p-value is used for decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*0eEorZYB8bfHDqzslBnqsQ.png" /><figcaption><a href="http://commres.net/wiki/_media/correlationtable.pdf">http://commres.net/wiki/_media/correlationtable.pdf</a></figcaption></figure><p>or you can use python:</p><pre>import scipy.stats as stats<br>import numpy as np<br><br># Parameters<br>n = 20  # Sample size<br>alpha = 0.05  # Significance level for two-tailed test<br>df = n - 2  # Degrees of freedom<br><br># Calculate critical t-value<br>t_critical = stats.t.ppf(1 - alpha / 2, df)<br><br># Calculate critical r-value<br>r_critical = np.sqrt(t_critical**2 / (t_critical**2 + df))<br><br># Display results<br>print(&quot;Degrees of Freedom (df):&quot;, df)<br>print(&quot;Critical t-value:&quot;, t_critical)<br>print(&quot;Critical r-value:&quot;, r_critical)<br></pre><p>4. Draw the conclusions:</p><ul><li>If p-value &lt;α (e.g., 0.05), reject H0​: Conclude that a significant linear relationship exists.</li><li>If p-value ≥α, fail to reject H0​: No evidence of a significant linear relationship.</li><li>If t-statistic ±t critical value, reject H0 (fall in the rejection area)</li><li>If r-value ± r-critical value, reject H0 (fall in the rejection area)</li></ul><p><strong>Marketing Example:</strong></p><p>A company wants to assess whether a significant linear relationship exists between <strong>ad spending</strong> and<strong> ROI</strong>.</p><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br># Example data: Ad spend (in $1000s) and ROI (Return on Investment, in %)<br>ad_spend = [5, 10, 15, 20, 25, 30]<br>roi = [8, 16, 22, 25, 28, 35]<br><br># Step 1: Calculate Pearson Correlation Coefficient and p-value<br>r, p_value = stats.pearsonr(ad_spend, roi)<br>n = len(ad_spend)  # Sample size<br><br># Step 2: Calculate t-statistic<br>t_stat = r * np.sqrt((n - 2) / (1 - r**2))<br><br># Step 3: Degrees of Freedom<br>df = n - 2<br><br># Step 4: Determine Critical Value (Two-Tailed Test, alpha = 0.05)<br>alpha = 0.05<br>t_critical = stats.t.ppf(1 - alpha / 2, df)<br><br># Step 5: Plot t-distribution and rejection regions<br>x = np.linspace(-4, 4, 1000)<br>t_dist = stats.t.pdf(x, df)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(x, t_dist, label=&quot;t-Distribution&quot;, color=&quot;blue&quot;)<br>plt.axvline(t_critical, color=&quot;red&quot;, linestyle=&quot;--&quot;, label=f&quot;Critical Value = {t_critical:.2f}&quot;)<br>plt.axvline(-t_critical, color=&quot;red&quot;, linestyle=&quot;--&quot;)<br>plt.fill_between(x, 0, t_dist, where=(x &lt; -t_critical) | (x &gt; t_critical), color=&quot;red&quot;, alpha=0.3, label=&quot;Rejection Region&quot;)<br>plt.axvline(t_stat, color=&quot;green&quot;, linestyle=&quot;--&quot;, label=f&quot;t-Statistic = {t_stat:.2f}&quot;)<br>plt.title(&quot;t-Distribution with Rejection Regions&quot;)<br>plt.xlabel(&quot;t-Value&quot;)<br>plt.ylabel(&quot;Probability Density&quot;)<br>plt.legend()<br>plt.grid()<br>plt.show()<br><br># Step 6: Scatter Plot of Ad Spend vs. ROI<br>plt.figure(figsize=(8, 6))<br>plt.scatter(ad_spend, roi, color=&quot;blue&quot;, label=&quot;Data Points&quot;)<br>plt.plot(ad_spend, np.poly1d(np.polyfit(ad_spend, roi, 1))(ad_spend), color=&quot;red&quot;, label=&quot;Best Fit Line&quot;)<br>plt.title(&quot;Ad Spend vs. ROI&quot;)<br>plt.xlabel(&quot;Ad Spend ($1000)&quot;)<br>plt.ylabel(&quot;ROI (%)&quot;)<br>plt.legend()<br>plt.grid()<br>plt.show()<br><br># Step 7: Print Results<br>print(&quot;Pearson Correlation Coefficient (r):&quot;, r)<br>print(&quot;p-Value:&quot;, p_value)<br>print(&quot;t-Statistic:&quot;, t_stat)<br>print(&quot;Critical t-Value (two-tailed, alpha = 0.05):&quot;, t_critical)<br><br># Step 8: Hypothesis Testing Conclusion<br>if abs(t_stat) &gt; t_critical:<br>    print(&quot;Conclusion: Reject the null hypothesis. There is a significant correlation between Ad Spend and ROI.&quot;)<br>else:<br>    print(&quot;Conclusion: Fail to reject the null hypothesis. No significant correlation between Ad Spend and ROI.&quot;)<br><br># Step 9: p-value Interpretation<br>if p_value &lt; alpha:<br>    print(&quot;Conclusion from p-value: There is strong evidence to reject the null hypothesis. Significant correlation between Ad Spend and ROI.&quot;)<br>else:<br>    print(&quot;Conclusion from p-value: There is insufficient evidence to reject the null hypothesis. No significant correlation between Ad Spend and ROI.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*y4QP7oyvjXveq3ex55DOGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsBbBsUXCuowONR4xkNFOg.png" /></figure><h4><strong>Chi-Square Test</strong></h4><p>The <strong>Chi-Square Test</strong> is a statistical test used to determine if there is a significant association between categorical variables or if the distribution of sample data differs from a hypothesized distribution. It is a non-parametric test, meaning it doesn’t assume a specific distribution for the data.</p><p>The test calculates the difference between <strong>observed</strong> and <strong>expected</strong> values under the assumption that the null hypothesis is true.</p><p>As you have already spotted from the definition, we have two types of chi-square tests:</p><ol><li><strong>Chi-Square Goodness of Fit Test</strong></li></ol><ul><li>Compares the observed distribution of a categorical variable to a hypothesized distribution.</li></ul><p><strong>2. Chi-Square Test for Independence</strong></p><ul><li>Tests whether two categorical variables are independent of each other.</li></ul><p><strong>Assumptions of the Chi-Square Test</strong></p><p>For both <strong>Goodness of Fit</strong> and <strong>Test for Independence</strong>, the assumptions are:</p><ul><li><strong>Independence</strong>: Each observation is independent of the others.</li><li><strong>Sample Size</strong>: The sample size should be large enough. In particular, each expected frequency should be at least 5 for the test to be valid.</li><li><strong>Categorical Data</strong>: The data should be categorical (nominal or ordinal).</li><li><strong>Expected Frequency</strong>: The expected frequency of observations in each category should not be too small (preferably greater than 5).</li></ul><p>For Chi-Square Goodness of Fit Test:</p><p>The H are:</p><ul><li><strong>Null Hypothesis</strong> (H0): The observed distribution matches the expected distribution.</li><li><strong>Alternative Hypothesis</strong> (HA​): The observed distribution does not match the expected distribution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*EYAdZ--PK8yz89i6JPh8Mw.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZth1x2zfzz7ATk1fLj72w.png" /></figure><p>For Chi-Square for Independence Test:</p><p>The H are:</p><ul><li><strong>Null Hypothesis</strong> (H0): The two variables are independent.</li><li><strong>Alternative Hypothesis</strong> (HA​): The two variables are dependent (associated).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFvYPFLEiCm5cnO5uSVteQ.png" /></figure><p>The expected values (denoted as Ei​ or Eij, depending on the test) are calculated based on the <strong>null hypothesis</strong>.</p><p>As for the other tests, once we have the test statistic, we have to find the critical value. The <strong>Chi-Square Critical Value</strong> is used to determine the threshold above which the Chi-Square statistic is considered significant. It is obtained from the <strong>Chi-Square distribution table</strong>, which depends on:</p><ul><li><strong>Degrees of Freedom</strong> (df):</li><li>For the <strong>Goodness of Fit</strong> test, degree of freedom is df=k−1, where k is the number of categories.</li><li>For the <strong>Test for Independence</strong>, degree of freedom is df=(r−1)×(c−1), where r is the number of rows and c is the number of columns in the contingency table.</li><li><strong>Significance Level</strong>: Common values are 0.050 or 0.01.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*wc6s0mnwZDCpvufxSm8dWg.png" /><figcaption><a href="https://www.scribbr.com/statistics/chi-square-distribution-table/">https://www.scribbr.com/statistics/chi-square-distribution-table/</a></figcaption></figure><p>or using python:</p><pre>import scipy.stats as stats<br><br># Parameters<br>alpha = 0.05  # Significance level (commonly used value)<br>df = 4  # Degrees of freedom (e.g., number of categories - 1)<br><br># Calculate the Chi-Square critical value<br>chi_square_critical_value = stats.chi2.ppf(1 - alpha, df)<br><br># Display the result<br>print(f&quot;Chi-Square Critical Value at α={alpha} with df={df}: {chi_square_critical_value:.3f}&quot;)</pre><p>The Chi-Square distribution:</p><ul><li><strong>Shape</strong>: The Chi-Square distribution is a <strong>positively skewed</strong> distribution that only takes non-negative values.</li><li><strong>Degrees of Freedom (df)</strong>: The shape of the Chi-Square distribution changes with degrees of freedom. As df increases, the distribution becomes more symmetric.</li><li>The Chi-Square distribution is used to calculate the <strong>p-value</strong> from the Chi-Square statistic and determine if the null hypothesis should be rejected.</li></ul><p>To reject or not the null hypothesis:</p><ul><li>If p-value &lt;α (e.g., 0.05), reject H0​: Depends on the test</li><li>If p-value ≥α, fail to reject H0​: Depends on the test</li><li>If chi-statistic &gt;t critical value, reject H0 (fall in the rejection area. Since the distribution is right-skewed we are only interested in the right-tail)</li></ul><p><strong>Marketing example:</strong></p><p>A <strong>marketing team</strong> for a new brand of flavoured sparkling water wants to test if <strong>consumer preference</strong> for the four available flavours (Lemon, Lime, Grapefruit, and Berry) is <strong>evenly distributed</strong> among the participants.</p><p>They conduct a <strong>taste test</strong> with <strong>200 participants</strong> and record their flavour preferences. The team wants to know if the distribution of preferences is uniform or if some flavours are preferred more than others.</p><p>Null Hypothesis (H0​):</p><ul><li>The <strong>consumer preference</strong> is <strong>evenly distributed</strong> across the four flavours (Lemon, Lime, Grapefruit, and Berry). In other words, each flavour has the same probability of being chosen.</li></ul><p>Alternative Hypothesis (HA​):</p><ul><li>The <strong>consumer preference</strong> is <strong>not evenly distributed</strong>. That is, some flavors are preferred more than others.</li></ul><pre>import scipy.stats as stats<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Observed data: Number of participants who preferred each flavor<br>observed_data = np.array([50, 60, 40, 50])<br><br># Total number of participants and number of flavors<br>total_participants = 200<br>num_flavors = 4<br><br># Expected value for each flavor (uniform distribution)<br>expected_data = np.full_like(observed_data, total_participants / num_flavors)<br><br># Perform the Chi-Square Goodness of Fit Test<br>chi2_stat, p_value = stats.chisquare(observed_data, expected_data)<br><br># Chi-Square critical value for 3 degrees of freedom at a 5% significance level<br>alpha = 0.05<br>chi2_critical = stats.chi2.ppf(1 - alpha, df=num_flavors-1)<br><br># Print results<br>print(f&quot;Chi-Square Statistic: {chi2_stat}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br>print(f&quot;Chi-Square Critical Value: {chi2_critical}&quot;)<br><br># Decision rule<br>if chi2_stat &gt; chi2_critical:<br>    print(&quot;Reject the null hypothesis: The consumer preference is not evenly distributed.&quot;)<br>else:<br>    print(&quot;Fail to reject the null hypothesis: The consumer preference is evenly distributed.&quot;)<br><br># --- Visualization ---<br><br># Plot observed vs expected values<br>flavors = [&#39;Lemon&#39;, &#39;Lime&#39;, &#39;Grapefruit&#39;, &#39;Berry&#39;]<br>x_pos = np.arange(len(flavors))<br><br>plt.figure(figsize=(10, 6))<br><br># Bar plot for observed and expected values<br>plt.bar(x_pos - 0.2, observed_data, 0.4, label=&#39;Observed&#39;, color=&#39;blue&#39;)<br>plt.bar(x_pos + 0.2, expected_data, 0.4, label=&#39;Expected&#39;, color=&#39;orange&#39;)<br><br># Adding labels and title<br>plt.xlabel(&#39;Flavor&#39;)<br>plt.ylabel(&#39;Number of Participants&#39;)<br>plt.title(&#39;Observed vs Expected Preferences for Flavors&#39;)<br>plt.xticks(x_pos, flavors)<br>plt.legend()<br><br># --- Chi-Square Distribution Plot ---<br>x = np.linspace(0, 15, 500)<br>y = stats.chi2.pdf(x, df=num_flavors-1)<br><br>plt.figure(figsize=(10, 6))<br><br># Plot Chi-Square distribution<br>plt.plot(x, y, label=&#39;Chi-Square Distribution (df=3)&#39;, color=&#39;green&#39;)<br><br># Plot the rejection region (right tail)<br>plt.fill_between(x, y, 0, where=(x &gt;= chi2_critical), color=&#39;red&#39;, alpha=0.5, label=&#39;Rejection Region&#39;)<br><br># Mark the calculated Chi-Square statistic on the distribution<br>plt.axvline(x=chi2_stat, color=&#39;blue&#39;, linestyle=&#39;dashed&#39;, label=f&#39;Chi-Square Statistic = {chi2_stat:.2f}&#39;)<br><br># Adding labels and title<br>plt.xlabel(&#39;Chi-Square Statistic&#39;)<br>plt.ylabel(&#39;Probability Density&#39;)<br>plt.title(&#39;Chi-Square Distribution with Rejection Region&#39;)<br>plt.legend()<br><br># Show the plots<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*K0nYGAPH3b_Y_B67SEFIDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzYvXFDXhdFM2kAPFAq9jg.png" /></figure><h4><strong>Mann-Whitney U Test</strong></h4><p>The Mann-Whitney U Test is a non-parametric statistical test that compares two independent groups to assess whether their population distributions differ significantly. It’s an alternative to the independent samples t-test when normality cannot be assumed. It compares the ranks of data points in two groups, rather than their means.</p><p><strong>Assumptions</strong></p><ol><li><strong>Independent Samples</strong>: The two groups being compared must be independent of each other.</li><li><strong>Ordinal or Continuous Data</strong>: Data should be at least ordinal (can be ranked) or continuous.</li><li><strong>Similar Shape</strong>: The two groups should have similar-shaped distributions (though not necessarily normal).</li><li><strong>Independence:</strong> The observations in each group are independent of each other.</li></ol><p><strong>When to Use:</strong></p><ul><li>When comparing two independent groups.</li><li>When the data is ordinal, not normally distributed, or violates the assumptions of a parametric test (e.g., t-test).</li></ul><p>The Mann-Whitney U statistic is calculated based on the sum of ranks assigned to the combined data from both groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Txxvn6_mxUbg9eJHx74FeQ.png" /></figure><p>For sample size (n1,n2 ≤20), the next step is to calculate the U critical value using the U test table (considering the alpha and the direction):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*6w_4Fwiwai3WQ1cSaXCmAQ.png" /><figcaption>example from <a href="https://real-statistics.com/statistics-tables/mann-whitney-table/">https://real-statistics.com/statistics-tables/mann-whitney-table/</a></figcaption></figure><p>To reject the H0, the U statistic has to be less or equal than U critical value, and the p- value follows the same logic for the other test.</p><p>For sample size (n1,n2 &gt; 20), the U-statistic is converted to a z-score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*BpkJSbq3iiOpowJX_hKl7g.png" /></figure><p>and the critical value corresponds to the <strong>z-critical value</strong> for the given confidence level (or significance level α\alphaα).</p><p>For example:</p><ul><li>For a two-tailed test with α=0.05, the critical z-values are −1.96 and +1.96.</li><li>For a one-tailed test with α=0.05, the critical z-value is +1.645 (upper tail) or −1.645 (lower tail).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*JdOO4zV4tfPPfxV064Rgug.png" /></figure><p><strong>Marketing Example:</strong></p><p>A marketing team ran two different ad campaigns, Campaign A and Campaign B, to increase customer satisfaction for a product. They want to compare the satisfaction scores from two independent groups (one group was exposed to Campaign A and the other to Campaign B).</p><p>The null hypothesis would state that there is <strong>no significant difference in satisfaction scores</strong> between the two groups, while the alternative hypothesis would suggest that there <strong>is a significant difference</strong>.</p><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br># Data for Customer Satisfaction Scores (simulated)<br># Campaign A (n = 10)<br>campaign_a = np.array([7, 8, 9, 6, 5, 8, 7, 6, 9, 8])<br><br># Campaign B (n = 10)<br>campaign_b = np.array([5, 6, 6, 7, 8, 5, 6, 5, 7, 6])<br><br># Perform the Mann-Whitney U Test<br>U_statistic, p_value = stats.mannwhitneyu(campaign_a, campaign_b, alternative=&#39;two-sided&#39;)<br><br># Print U-statistic and p-value<br>print(f&quot;U-statistic: {U_statistic}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br><br># --- Visualization ---<br><br># Define the number of samples in each group<br>n_a = len(campaign_a)<br>n_b = len(campaign_b)<br><br># For small samples, critical value is based on the U-table (not calculated via z)<br># For simplicity, we&#39;ll use scipy&#39;s mannwhitneyu method to get the critical value<br>critical_value = min(stats.mannwhitneyu(campaign_a, campaign_b).statistic, n_a * n_b)<br><br># Plot the Mann-Whitney U Distribution<br>plt.figure(figsize=(8, 6))<br><br># Set U-values range<br>u_values = np.linspace(0, n_a * n_b, 100)<br><br># Plotting the U-distribution curve<br>plt.plot(u_values, stats.norm.pdf(u_values, np.mean(u_values), np.std(u_values)), label=&#39;U Distribution&#39;, color=&#39;purple&#39;)<br><br># Highlighting the U-statistic and critical value lines<br>plt.axvline(U_statistic, color=&#39;blue&#39;, linestyle=&#39;dashed&#39;, label=f&#39;U-statistic: {U_statistic}&#39;)<br>plt.axvline(critical_value, color=&#39;orange&#39;, linestyle=&#39;dashed&#39;, label=f&#39;Critical Value: {critical_value}&#39;)<br><br># Adding rejection area (left side of the critical value)<br>plt.fill_between(u_values, 0, stats.norm.pdf(u_values, np.mean(u_values), np.std(u_values)), <br>                 where=(u_values &lt;= critical_value), color=&#39;red&#39;, alpha=0.3, label=&quot;Rejection Area&quot;)<br><br># Customize plot<br>plt.title(&#39;Mann-Whitney U Distribution with Rejection Areas&#39;)<br>plt.xlabel(&#39;U Value&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.legend()<br>plt.grid(True)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*L7mscdKZlA6VVDpBE_2vcg.png" /></figure><h4><strong>Kruskal-Wallis Test</strong></h4><p>The Kruskal-Wallis test is a non-parametric test used to compare three or more independent groups. It’s the non-parametric equivalent of a one-way ANOVA. Unlike ANOVA, it doesn’t assume that the data are normally distributed. Instead, it works by ranking all the data points from all groups together and then comparing the sums of the ranks in each group. This test extends the <strong>Mann-Whitney U Test</strong> to more than two groups. It works the sum of ranks rather than the groups means.</p><p><strong>Assumptions:</strong></p><ol><li>The observations are independent of each other.</li><li>The dependent variable is ordinal or continuous but not necessarily normally distributed.</li><li>The distributions of the groups have the same shape, but the actual distributions don’t have to be the same.</li></ol><p><strong>When to Use Kruskal-Wallis Test:</strong></p><ul><li>When you have more than two groups and want to compare their distributions.</li><li>The data is ordinal, or the assumption of normality for a parametric test (like ANOVA) is not met.</li><li>The groups are independent (no repeated measures).</li></ul><p>The statistic for this test is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1jPKrQyLnX7aj1WWsGhaA.png" /></figure><p>and the distribution used is the <strong>Chi-Square distribution, </strong>hence<strong> </strong>we will use the <strong>Chi-Square table </strong>for calculating the<strong> </strong>critical value with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q7ccGn1F7HwqVgwxuzn3A.png" /></figure><p>at any significant level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*wc6s0mnwZDCpvufxSm8dWg.png" /><figcaption><a href="https://www.scribbr.com/statistics/chi-square-distribution-table/">https://www.scribbr.com/statistics/chi-square-distribution-table/</a></figcaption></figure><p>In terms of rules for rejecting the null hypothesis, we can use the same as for the Chi-Square Test. So:</p><ul><li>If p-value &lt;α (e.g., 0.05), reject H0</li><li>If p-value ≥α, fail to reject H0​</li><li>If H-statistic &gt;Chi critical value, reject H0 (fall in the rejection area. Since the distribution is right-skewed we are only interested in the right-tail)</li></ul><p><strong>Marketing Example:</strong></p><p>A marketing team is evaluating the effectiveness of three different promotional campaigns (Campaign A, Campaign B, and Campaign C) in terms of customer satisfaction. They have conducted a survey asking customers to rate their satisfaction level on a scale from 1 to 10 after being exposed to each of these campaigns. The goal is to determine if there are significant differences in customer satisfaction between the three campaigns.</p><ul><li><strong>Campaign A:</strong> Traditional TV ads</li><li><strong>Campaign B:</strong> Social media ads</li><li><strong>Campaign C:</strong> Influencer partnerships</li></ul><p>Null Hypothesis (H₀):</p><p>There is no difference in customer satisfaction between the three campaigns. In other words, the median satisfaction score for all campaigns is the same.</p><p>Alternative Hypothesis (H₁):</p><p>At least one campaign results in different customer satisfaction compared to the others. The median satisfaction score is different for at least one campaign.</p><pre>import pandas as pd<br>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br># Sample Data: Satisfaction scores for three campaigns<br>data = {<br>    &#39;Campaign A&#39;: [6, 7, 8, 5, 6, 7, 8, 6, 5, 6],<br>    &#39;Campaign B&#39;: [8, 9, 7, 6, 8, 9, 7, 8, 9, 8],<br>    &#39;Campaign C&#39;: [4, 5, 6, 7, 5, 6, 6, 7, 4, 5]<br>}<br><br># Create DataFrame<br>df = pd.DataFrame(data)<br><br># Perform Kruskal-Wallis H Test<br>H_statistic, p_value = stats.kruskal(df[&#39;Campaign A&#39;], df[&#39;Campaign B&#39;], df[&#39;Campaign C&#39;])<br><br># Print the test statistic and p-value<br>print(&quot;Kruskal-Wallis Test&quot;)<br>print(&quot;H-statistic:&quot;, H_statistic)<br>print(&quot;P-value:&quot;, p_value)<br><br># Critical value (Chi-Square distribution) for df=2 (3 groups - 1 = 2 degrees of freedom) and alpha = 0.05<br>critical_value = stats.chi2.ppf(1 - 0.05, df=2)<br>print(&quot;Critical value (from Chi-Square distribution):&quot;, critical_value)<br><br># Interpretation<br>if H_statistic &gt; critical_value:<br>    print(&quot;Reject the null hypothesis: There is a significant difference between the campaigns.&quot;)<br>else:<br>    print(&quot;Fail to reject the null hypothesis: There is no significant difference between the campaigns.&quot;)<br><br># Visualization: Kruskal-Wallis Test results<br># Boxplot of satisfaction scores for the campaigns<br>plt.figure(figsize=(8, 6))<br>plt.boxplot([df[&#39;Campaign A&#39;], df[&#39;Campaign B&#39;], df[&#39;Campaign C&#39;]], labels=[&#39;Campaign A&#39;, &#39;Campaign B&#39;, &#39;Campaign C&#39;])<br>plt.title(&quot;Customer Satisfaction Scores by Campaign&quot;)<br>plt.ylabel(&quot;Satisfaction Score&quot;)<br><br># Plot the Chi-Square distribution and highlight the rejection area<br>x = np.linspace(0, 10, 1000)<br>y = stats.chi2.pdf(x, df=2)<br><br>plt.figure(figsize=(8, 6))<br>plt.plot(x, y, label=&quot;Chi-Square Distribution (df=2)&quot;, color=&#39;blue&#39;)<br>plt.fill_between(x, y, where=(x &gt; critical_value), color=&#39;red&#39;, alpha=0.5, label=&quot;Rejection Region&quot;)<br>plt.axvline(x=critical_value, color=&#39;red&#39;, linestyle=&#39;--&#39;, label=f&quot;Critical Value = {critical_value:.2f}&quot;)<br>plt.axvline(x=H_statistic, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=f&quot;H-statistic = {H_statistic:.2f}&quot;)<br>plt.title(&quot;Kruskal-Wallis Test: Chi-Square Distribution and Rejection Area&quot;)<br>plt.xlabel(&quot;Chi-Square Value&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend(loc=&#39;upper right&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Vz7EIDfRx5fQjEpKvAL7rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*3HzMU2Aw96bKiBy3ePDR_A.png" /></figure><h4><strong>Spearman Rank Correlation “Test”</strong></h4><p>The <strong>Spearman Rank Correlation</strong> is a non-parametric test that determines if there is a significant monotonic relationship between two variables. The monotonic relationship means that as one variable increases, the other variable constantly increases or decreases. This can be linear or non linear. It is used when the assumptions of Pearson correlation (e.g., linearity and normality) are not met. It is based on the ranks of the values rather than the actual values themselves.</p><p><strong>Assumptions:</strong></p><ol><li>The variables are ordinal or continuous.</li><li>The relationship between the variables is monotonic (i.e., as one variable increases, the other either increases or decreases).</li><li>The data does not need to be normally distributed.</li></ol><p><strong>Interpretation of the Spearman Rank Correlation:</strong></p><ul><li>ρ=1: Perfect positive monotonic relationship</li><li>ρ=−1: Perfect negative monotonic relationship</li><li>ρ=0: No monotonic relationship</li><li>A value close to 1 or -1 indicates a strong relationship, while a value closer to 0 indicates a weak relationship.</li></ul><p>The Spearman rank correlation coefficient (ρ or rs) is calculated using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f4FVhgqzuBIYNOD4jRPbA.png" /></figure><p>Once you have the test statistic, you have to find the critical value.</p><p>Here we have two cases:</p><p><strong>Small sample size (n &lt; 30)</strong></p><p>1. find the value using Spearman’s critical value table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*ZaPyMflyzWFkfF19b3md3w.png" /><figcaption><a href="https://real-statistics.com/statistics-tables/spearmans-rho-table/">https://real-statistics.com/statistics-tables/spearmans-rho-table/</a></figcaption></figure><p>2. compare your calculated ρ with the critical value and compare the p-value with alpha.</p><ul><li>If ∣ρ∣≥| critical value, <strong>reject the null hypothesis</strong> (there is a significant relationship).</li><li>If ∣ρ∣&lt;| critical value, <strong>fail to reject the null hypothesis</strong> (no significant relationship).</li><li>If the p-value is less than 0.05, we reject the null hypothesis, suggesting a significant monotonic relationship. If it’s greater than 0.05, we fail to reject the null hypothesis.</li></ul><p><strong>Large sample size (n ≥30)</strong></p><ol><li>the ρ statistic can be approximated using a normal distribution and z-score.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*foLNpMHV-l3PXZZSn7zl4Q.png" /></figure><p>2. find the critical value using the standard normal distribution table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*HZCM10_NywHFrVXxqd78QA.png" /><figcaption><a href="https://www.craftonhills.edu/current-students/tutoring-center/mathematics-tutoring/distribution_tables_normal_studentt_chisquared.pdf">https://www.craftonhills.edu/current-students/tutoring-center/mathematics-tutoring/distribution_tables_normal_studentt_chisquared.pdf</a></figcaption></figure><p>Determining if rejecting the null hypothesis depends on the “direction of the test”</p><ul><li>two-tailed = H0 != H1 meaning the z-score has to exceed the critical value in both directions +-</li><li>one-tailed = H0 greater than H1 or vice-versa meaning the z-score has to be greater or lower than the critical value in the direction selected.</li></ul><p><strong>Marketing Example:</strong></p><p>A marketing team wants to assess whether there’s a significant correlation between <strong>customer satisfaction ratings</strong> (ordinal scale: 1 to 5) and <strong>purchase frequency</strong> (ordinal scale: 1 = rare, 5 = frequent).</p><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br># --- Data: Ordinal Ratings ---<br>satisfaction = [5, 4, 3, 4, 2, 1, 3, 2]  # Customer satisfaction ratings<br>purchase_frequency = [5, 4, 3, 3, 2, 1, 3, 2]  # Purchase frequency ratings<br><br># --- Calculate Spearman&#39;s Rank Correlation ---<br>rho, p_value = stats.spearmanr(satisfaction, purchase_frequency)<br><br># Critical value for Spearman&#39;s rho (small sample, n=8, alpha=0.05, two-tailed)<br>critical_value = 0.738  # Looked up from Spearman&#39;s critical value table for n=8, alpha=0.05<br><br># --- Visualization of Spearman Distribution and Rejection Area ---<br>x = np.linspace(-1, 1, 500)<br>critical_region = np.abs(x) &gt;= critical_value<br>plt.figure(figsize=(10, 6))<br>plt.plot(x, stats.beta.pdf((x + 1) / 2, len(satisfaction) - 1, len(purchase_frequency) - 1), label=&quot;Spearman Distribution&quot;, color=&quot;blue&quot;)<br>plt.fill_between(x, 0, stats.beta.pdf((x + 1) / 2, len(satisfaction) - 1, len(purchase_frequency) - 1), where=critical_region, color=&quot;red&quot;, alpha=0.5, label=&quot;Rejection Region&quot;)<br>plt.axvline(rho, color=&quot;green&quot;, linestyle=&quot;--&quot;, label=f&quot;Observed rho: {rho:.2f}&quot;)<br>plt.title(&quot;Small Sample Spearman Distribution and Rejection Region&quot;)<br>plt.xlabel(&quot;Spearman&#39;s rho&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.show()<br><br># --- Results ---<br>print(&quot;Spearman Rank Correlation Test (Small Sample)&quot;)<br>print(f&quot;Spearman&#39;s rho: {rho:.2f}&quot;)<br>print(f&quot;p-value: {p_value:.4f}&quot;)<br>print(f&quot;Critical value: ±{critical_value}&quot;)<br>print(&quot;Result: Reject H0&quot; if abs(rho) &gt;= critical_value else &quot;Result: Fail to Reject H0&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*hqa6U7FvpthKO8PWPRW15w.png" /></figure><p>If you’ve made it this far, you’re a hero! Hope you enjoyed this loooong blog post! See you next time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*XdXptG3Q5J6V0ef2" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6566d5f8899" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handy Statistics Part 2: All you have to know about Descriptive Statistics]]></title>
            <link>https://medium.com/@maranosabrina9/handy-statistics-part-2-all-you-have-to-know-about-descriptive-statistics-32d70ab97741?source=rss-6bb18e636d19------2</link>
            <guid isPermaLink="false">https://medium.com/p/32d70ab97741</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[datascience-training]]></category>
            <dc:creator><![CDATA[MaranoSabrina]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 12:03:29 GMT</pubDate>
            <atom:updated>2025-07-25T14:36:52.327Z</atom:updated>
            <content:encoded><![CDATA[<p>A complete guide easy explained with Python examples</p><p>What you will find:</p><ol><li>Measure of Central Tendency</li><li>Measure of Dispersion</li><li>Descriptive Analysis for Categorical Data</li><li>Measure of Distribution</li><li>Visualizations</li><li>Challenges and Takeaways</li></ol><p>Welcome to an extensive guide on Descriptive Statistics.</p><p>Today we will talk about the core of this kind of statistics, what we can do and the insights we can derive from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ynyHo6jKfSSdCEiw.gif" /></figure><p>As we briefly saw in the previous <a href="https://medium.com/@maranosabrina9/handy-statistics-part-1-types-of-statistics-in-data-science-and-why-they-are-so-important-1b138baa0e95">part</a>, Descriptive Statistics aims to summarize and describe the dataset. It answers questions like “What does the data look like?”.</p><p>The key concepts are:</p><ul><li>measure of central tendency</li><li>measure of the variability</li><li>measure the shape of the distribution</li><li>data visualization</li></ul><p>Before diving into it we need to step back and focus on an important concept: <strong>outliers.</strong></p><p>The outliers are defined as extreme values in a dataset, meaning or extremely low or extremely high compared to the rest or vice versa.</p><p>They can distort results and analyses, but also provide valuable insights</p><p>Outliers can be generated by mistake or simply be unusual elements. They can be treated differently depending on the context. In anomaly detection, they are the core of the analysis. In our case, they heavily influence the measures of central tendency and dispersion, leading to misleading interpretations.</p><h4><strong>1.Measure of Central Tendency</strong></h4><p>With “Central Tendency”, we refer to a single value that represents the centre of the dataset, helping to summarise data effectively. The three measures are mean, median and mode.</p><ol><li><strong>Mean</strong></li></ol><p>The most common mean, or average, is the <strong>arithmetic mean</strong> and it is calculated by adding up all data points and dividing by the total number of data points. Useful for normally distributed data without significant outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*bazCXin-4puOWow6JbheBA.png" /></figure><p>where <em>xi</em> are the data points, and <em>n</em> is the number of data points.</p><pre>import numpy as np<br>data = [10, 20, 30, 40]<br>mean = np.mean(data)<br>print(&quot;Arithmetic Mean:&quot;, mean)<br>Arithmetic Mean: 25.0</pre><p><strong>Scenario:</strong></p><p>You’re working at an online fashion retail store and want to calculate the <strong>average revenue per customer</strong> from a recent marketing campaign. You have the revenue data for five customers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*mcgi1sKXvd_NSH0hgyjCDg.png" /></figure><p>Your goal is to find the arithmetic mean of these values to determine how much revenue, on average, each customer generated.</p><pre># Revenue data<br>revenues = [100, 150, 200, 50, 250]<br><br># Calculate arithmetic mean<br>average_revenue = np.mean(revenues)<br><br>print(f&quot;Average Revenue per Customer: ${average_revenue:.2f}&quot;)<br>Average Revenue per Customer: $150.00</pre><p>The <strong>geometric mean</strong> is the nth root of the product of n data points. It captures multiplicative relationships, such as growth rates or percentages. The geometric mean is particularly suited for analysing situations where values multiply or grow over time, rather than simply being added together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*iDS5EbApXbCLAlw7kTSexg.png" /></figure><pre>from scipy.stats import gmean<br>data = [1.1, 1.2, 1.3]<br>geometric_mean = gmean(data)<br>print(&quot;Geometric Mean:&quot;, round(geometric_mean,3))<br>Geometric Mean: 1.197</pre><p>In many real-world scenarios, like <strong>investment returns</strong>, <strong>population growth</strong>, or <strong>percentage changes</strong>, the effects of growth are multiplicative. For example, if a stock grows by 10% in the first year and then by 20% in the second year, the total growth isn’t a simple average of 15% per year. Instead, each year’s growth builds on the previous year — a concept called <em>compounding</em>.</p><p><strong>Scenario:</strong></p><p>You’re analysing the monthly revenue growth rate for an online fashion retail store over five months. The growth rates are expressed as percentages relative to the previous month, and the goal is to calculate the <strong>average growth rate</strong> to understand the compounded growth trend over these months:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*im_3jAZrup9M-WfYVOrx7Q.png" /></figure><p>The geometric mean is ideal for this scenario because it accounts for <strong>multiplicative effects</strong> over time. Unlike the arithmetic mean, which might give a misleading result, the geometric mean considers the compounding nature of growth rates.</p><pre># Growth rates as decimal equivalents<br>growth_rates = [1.05, 1.10, 1.08, 0.98, 1.06]<br><br># Calculate geometric mean<br>geo_mean = gmean(growth_rates)<br><br># Convert back to percentage<br>average_growth_rate = (geo_mean - 1) * 100<br><br>print(f&quot;Average Growth Rate: {average_growth_rate:.2f}%&quot;)<br>Average Growth Rate: 5.32%</pre><p>Over the five months, the average monthly growth rate (compounded) was 5.32%. This reflects the overall trend, smoothing out the variations caused by ups and downs in individual months. If you used the arithmetic mean, the result would likely overestimate the average growth rate, as it doesn’t account for the multiplicative nature of growth.</p><p>The <strong>harmonic mean</strong> is calculated as the reciprocal of the arithmetic mean of reciprocals. It emphasises smaller values in a dataset. It is used for rates or ratios, such as cost-per-unit or conversion rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*mXlUnz_0xNk5Bkeoowk5sA.png" /></figure><p>where n is the number of values and xi​ are the data points.</p><pre>from scipy.stats import hmean<br>data = [10, 20, 30]<br>harmonic_mean = hmean(data)<br>print(&quot;Harmonic Mean:&quot;, harmonic_mean)</pre><p><strong>Scenario:</strong></p><p>You’re running an online marketing campaign across three platforms, and you want to calculate the <strong>average conversion rate</strong>. Each platform has a different number of impressions and conversions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JD4BzJS4WIcnFV3A9-AFFw.png" /></figure><p>Smaller rates (low-conversion platforms) have a larger impact on the harmonic mean. This ensures you don’t overestimate the average due to a high-performing platform with fewer impressions (Platform B).</p><pre>from scipy.stats import hmean<br># Conversion rates as percentages<br>conversion_rates = [1.0, 2.5, 1.0]<br><br># Convert percentages to decimals<br>conversion_rates_decimal = [rate / 100 for rate in conversion_rates]<br><br># Calculate harmonic mean<br>harmonic_mean_rate = hmean(conversion_rates_decimal)<br><br># Convert back to percentage for interpretation<br>harmonic_mean_rate_percentage = harmonic_mean_rate * 100<br><br>print(f&quot;The harmonic mean of the conversion rates is: {harmonic_mean_rate_percentage:.2f}%&quot;)<br>The harmonic mean of the conversion rates is: 1.25%</pre><p>The <strong>weighted mean</strong> assigns weights to data points, giving some values more influence over the final average. Useful when different data points contribute unequally, like calculating the average satisfaction score by giving more weight to recent reviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*ZM-shHxheAj72tulUuaQnA.png" /></figure><p>where wi​ are the weights.</p><pre>import numpy as np<br>values = [10, 20, 30]<br>weights = [1, 2, 3]  # Assign weights<br>weighted_mean = np.average(values, weights=weights)<br>print(&quot;Weighted Mean:&quot;, round(weighted_mean,2))<br>Weighted Mean: 23.33<br><br>#othersolution<br>data = {&#39;Values&#39;: [10, 20, 30],<br>        &#39;Weights&#39;: [1, 2, 3]}<br><br>df = pd.DataFrame(data)<br>weighted_average = round(sum(df[&#39;Values&#39;] * df[&#39;Weights&#39;]) / sum(df[&#39;Weights&#39;]),2)<br>weighted_average</pre><p>So there are two main motivations for using the weighted mean:</p><ul><li>Some values are intrinsically more valuable than others</li><li>The data collected doesn’t equally represent the different groups we are interested in measuring. For example, we can give higher weight to the values of the underrepresented group.</li></ul><p><strong>Scenario:</strong></p><p>You’re analysing the performance of a marketing campaign across three platforms: Facebook, Instagram, and Google Ads. The investment for each platform is different, and you want to calculate the average cost per click (CPC) while giving more weight to platforms with a higher investment. This allows you to reflect the relative importance of each platform’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYukvmIgMlNvuryFCGQ1YQ.png" /></figure><p>In this case, since Google Ads has the largest investment, its performance (CPC) should have more influence on the overall average.</p><pre># Data for the campaign<br>investment = [5000, 2000, 10000]  # Investment in each platform<br>cpc = [0.50, 0.40, 0.30]  # CPC for each platform<br><br># Calculate the weighted mean CPC<br>weighted_mean_cpc = sum(investment[i] * cpc[i] for i in range(len(investment))) / sum(investment)<br><br>print(f&quot;The weighted mean CPC across all platforms is: ${weighted_mean_cpc:.2f}&quot;)<br>The weighted mean CPC across all platforms is: $0.37</pre><p>In this case, platforms with higher investments (like Google Ads with $10,000) should have more influence on the average CPC because they account for a larger portion of the total campaign budget. The weighted mean ensures that the cost per click from each platform is reflected proportionally to the investment made in that platform. This gives you a more accurate representation of the campaign’s overall cost-efficiency.</p><p>The <strong>trimmed mean</strong> formula is used to calculate the mean (average) of a dataset after removing a certain percentage of the lowest and highest values. It is particularly useful when you want to minimize the effect of outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*X-cJzTEhkdEk5P9KtMJP8A.png" /></figure><ul><li>xi​ is the remaining data points after trimming.</li><li>n is the total number of data points in the original dataset.</li><li>k is the number of data points to be removed from both the lower and upper ends of the sorted dataset.</li><li>k is calculated as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*78yIdupSmAcHrdJXcZSZaA.png" /></figure><p>where p is the percentage of data to trim (e.g., 10% for 10% trimming).</p><pre>from scipy.stats import trim_mean<br>data = [1, 5, 10, 20, 30, 40, 1000]  # Contains an outlier<br>trimmed_mean = trim_mean(data, proportiontocut=0.2)  # Remove 20% extremes<br>print(&quot;Trimmed Mean:&quot;, trimmed_mean)<br>Trimmed Mean: 21.0<br><br>#where proportiontocut=0.2 defines the percentage we selected (20%)</pre><p>How to calculate and interpret it?</p><ol><li><strong>Sorting the Data</strong>: The first step in calculating the trimmed mean is to <strong>sort</strong> the data in ascending order:</li><li><strong>Trimming the Data</strong>: You are removing <strong>20%</strong> of the data points, but you split it into <strong>10% from the beginning</strong> and <strong>10% from the end</strong>:</li><li><strong>10% of 7 data points</strong> is approximately <strong>0.7</strong> data points. You round that up to <strong>1 data point</strong> from each end.</li><li><strong>Calculating the Trimmed Mean</strong>: Now, you calculate the <strong>mean</strong> of the remaining data</li></ol><p>Thus, the <strong>trimmed mean</strong> for this dataset with 20% trimming is <strong>21</strong>.</p><p><strong>Scenario:</strong></p><p>You are a marketing analyst, and you’re looking at the ages of customers who made purchases during a specific marketing campaign. However, the dataset contains some very young and very old customers who may not reflect the typical customer profile. To get a better sense of the <strong>central tendency of customer age</strong>, you decide to use a <strong>trimmed mean</strong>.</p><pre>import numpy as np<br>from scipy import stats<br><br># Define the dataset<br>ages = [15, 18, 25, 28, 30, 32, 35, 40, 45, 50, 60, 100, 105, 110]<br><br># Apply trimmed mean with 20% trim (10% from each end)<br>trimmed_mean = stats.trim_mean(ages, proportiontocut=0.1)<br><br># Output the result<br>print(&quot;Trimmed Mean (20% trimming):&quot;, trimmed_mean)<br>Trimmed Mean (20% trimming): 36.0</pre><p>In this dataset, the values 100, 105, and 110 are extreme outliers compared to the rest of the data. You decided to trim 20% of the extreme ages (10% from each end). This means we removed the lowest 10% of values (15, 18) and the highest 10% (100, 105, 110) before calculating the mean.</p><p>The <strong>trimmed mean</strong> for the ages is <strong>36.0</strong>, which better represents the <strong>central tendency of customer age</strong> without the skew caused by the extreme outliers. Without the trimming, the mean would be 50, with the consequence of not reflecting properly the average customer age.</p><p>To sumup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*lidc2QKxihfk2DlORbkN4g.png" /></figure><p><strong>2. Median</strong></p><p>The <strong>median </strong>is the second way to measure the central tendency, and it is the central value in a sorted dataset where 50% of the data falls above and the other 50% falls below. The median is defined as a <strong>“robust metric” </strong>because it is not influenced by the outliers like the mean.</p><p>In an even dataset, we take the two middle values and calculate the average such as in a list like 1,2,3,4 the median is (2+3)/2 = 2.5 while in an odd dataset we take the middle value such as 1,2,3 the median is 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Dtwlk6x5Q4uO4pwzwAXpKw.png" /></figure><pre>import numpy as np<br># Customer spending data (in dollars)<br>spending = [20, 30, 50, 100, 1000]  # Contains an outlier<br><br># Calculate the median<br>median_spending = np.median(spending)<br>print(f&quot;Median Customer Spending: ${median_spending}&quot;)<br>Median Customer Spending: $50</pre><p><strong>Scenario:</strong></p><p>A retail store launches a marketing campaign and records daily customer spending. Most customers spend modestly, but a few high-spending VIP customers skew the data. Calculating the <strong>median spending</strong> helps identify the <strong>typical customer behaviour</strong> without being distorted by a few exceptionally large purchases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*KioOjhnQd0StFe7z865BCw.png" /></figure><p>The mean is heavily skewed by the <strong>VIP customer</strong>, suggesting an inaccurately high average. However, the <strong>median</strong> is 80, representing the <strong>typical daily spending</strong> more accurately.</p><pre>import numpy as np<br><br># Daily spending data from a marketing campaign (contains an outlier)<br>spending = [50, 60, 100, 5000, 80]<br><br># Calculate the mean<br>mean_spending = np.mean(spending)<br><br># Calculate the median<br>median_spending = np.median(spending)<br><br>print(f&quot;Mean Daily Spending: ${mean_spending:.2f}&quot;)<br>print(f&quot;Median Daily Spending: ${median_spending:.2f}&quot;)<br><br># Interpretation<br>if mean_spending &gt; 2 * median_spending:<br>    print(&quot;The mean is heavily influenced by outliers.&quot;)<br>else:<br>    print(&quot;The mean and median are close, indicating no significant outliers.&quot;)<br>Mean Daily Spending: $1058.00<br>Median Daily Spending: $80.00<br>The mean is heavily influenced by outliers.</pre><p><strong>3.Mode</strong></p><p>The third measure of central tendency is the <strong>mode</strong>. It represents the most common value in a dataset and it is useful to identify trends or preferences especially when the mean calculation is not possible like for categorical data.</p><p>Unlike mean and median, the mode can have multiple values or none if all values are unique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*yW1d-5pDr3svYIlHQg_ytQ.png" /></figure><ul><li><strong>Unimodal</strong>: The dataset has one mode (a single most frequent value).</li><li><strong>Bimodal</strong>: The dataset has two modes (two distinct values occurring with the same highest frequency).</li><li><strong>Multimodal</strong>: The dataset has more than two modes (multiple values occurring with the same highest frequency).</li><li><strong>No Mode</strong>: If no value repeats, the dataset has no mode.</li></ul><pre>from scipy.stats import mode<br><br># Product categories from a customer purchase dataset<br>product_categories = [<br>    &quot;T-shirts&quot;, &quot;Jeans&quot;, &quot;T-shirts&quot;, &quot;Dresses&quot;, &quot;T-shirts&quot;, &quot;Jeans&quot;, &quot;Dresses&quot;, &quot;Jeans&quot;, &quot;T-shirts&quot;, &quot;Jeans&quot;<br>]<br><br># Calculate the mode<br>most_frequent_category, frequency = mode(product_categories)<br><br>print(f&quot;The most purchased product category is &#39;{most_frequent_category[0]}&#39; with {frequency[0]} purchases.&quot;)<br></pre><p>or</p><pre>from collections import Counter<br><br># Dataset of customer purchases<br>product_categories = [<br>    &quot;T-shirts&quot;, &quot;Jeans&quot;, &quot;T-shirts&quot;, &quot;Dresses&quot;, &quot;Jeans&quot;, &quot;T-shirts&quot;, <br>    &quot;Dresses&quot;, &quot;Jeans&quot;, &quot;T-shirts&quot;, &quot;Dresses&quot;, &quot;Jeans&quot;, &quot;Dresses&quot;<br>]<br><br># Count frequencies<br>category_counts = Counter(product_categories)<br>most_common = category_counts.most_common()<br><br># Identify modes<br>max_frequency = most_common[0][1]<br>modes = [item for item, count in most_common if count == max_frequency]<br><br># Determine modality<br>if len(modes) == 1:<br>    modality = &quot;Unimodal&quot;<br>elif len(modes) == 2:<br>    modality = &quot;Bimodal&quot;<br>else:<br>    modality = &quot;Multimodal&quot;<br><br>print(f&quot;Modes: {modes}&quot;)<br>print(f&quot;Modality: {modality}&quot;)</pre><h3><strong>2.Measure of the variability</strong></h3><p>The location of the centre is just one dimension to summarise the dataset.</p><p>The second one is the <strong>variability, </strong>also known as <strong>dispersion, </strong>which tells us how the data are clustered or spread out from the mean, meaning the dispersion shows how much the data points differ from each other. A dataset with low dispersion means the values are close to each other or the average, while a dataset with high dispersion means the values are spread out.</p><p>There are four ways to measure the variability: range, standard deviation, variance and IQR (Interquartile Range).</p><ol><li><strong>Range</strong></li></ol><p>The <strong>range </strong>is the simplest measure of dispersion. It tells you the difference between the <strong>highest</strong> and <strong>lowest</strong> values in the dataset. It gives a quick idea of how spread out the values are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Ca4ZlqP1k8YuemOsSHG0mg.png" /></figure><p><strong>How to interpret</strong>:</p><ul><li>If the range is large, it means the data points are spread far apart, indicating high variability, so there is a wide spread between the smallest and largest values.</li><li>If the range is small, it means the data points are close to each other and tightly packed, indicating low variability.</li></ul><pre># Sample data<br>data = [3, 25, 50, 75,60, 100, 125, 150, 200, 3000]<br><br># Calculate range<br>data_range = max(data) - min(data)<br><br># Print result<br>print(&quot;Range of data:&quot;, data_range)<br>Range of data: 2997 #indicating high variability </pre><p>This measure is heavily <strong>sensitive to outliers</strong>. In this case, the value 3000 skews the measure, making the data appear much more variable than it truly is for most of the values.</p><p><strong>Scenario:</strong></p><p>Imagine you are analysing customer spending in a <strong>retail store</strong>. The spending data in dollars is:</p><pre># Sample data: Customer spending in dollars<br>customer_spending = [25, 50, 75, 100, 125, 150, 200]<br><br># Calculate range<br>data_range = max(customer_spending) - min(customer_spending)<br><br># Print result<br>print(&quot;Range of customer spending:&quot;, data_range)<br>Range of customer spending: 175</pre><p>A range of <strong>$175</strong> indicates a <strong>large spread</strong> in customer spending. This could mean that the store attracts both <strong>low-spending</strong> and <strong>high-spending</strong> customers. From these insights, you can tailor personalised marketing strategies. Yet, the range provides a <strong>quick overview of variability</strong>, but it doesn’t account for how the data is distributed.</p><p><strong>2. Standard Deviation</strong></p><p>With the term “<strong>deviations</strong>”, we mean how far the data points are from the mean of the dataset, also known as <strong>residuals </strong>or<strong> errors</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*uXQ_AYweiv6VoCKR.gif" /></figure><p>The Standard Deviation comes from the deviation and the idea of “standardizing” or <strong>normalizing</strong> these deviations to provide a consistent measure of variability across different datasets. The word <strong>“standard”</strong> indicates that the deviation has been “standardized” or made consistent in a way that allows comparison across different datasets. Instead of just summing the raw deviations, we <strong>square</strong> them to eliminate negative values and amplify larger deviations (this also makes the measurement sensitive to larger differences). Then, we take the <strong>square root</strong> of the <strong>variance</strong> (which is the mean of squared deviations), so that the result is in the <strong>same unit</strong> as the original data (because variance is in squared units). This makes the standard deviation easy to interpret and explain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*iHKZ9NV32tNyv31EX-dBCQ.png" /></figure><p>Where:</p><ul><li>xi​: Each data point</li><li>xˉ: Mean of the data</li><li>n: Total number of data points</li></ul><pre>import numpy as np<br><br># Example dataset: Weekly sales (in units)<br>sales = [50, 60, 55, 70, 65, 80, 75]<br><br># Calculate mean<br>mean_sales = np.mean(sales)<br><br># Calculate standard deviation<br>std_dev_sales = np.std(sales)<br><br>print(&quot;Mean of sales:&quot;, mean_sales)<br>print(&quot;Standard Deviation of sales:&quot;, std_dev_sales)<br>Mean of sales: 65.0<br>Standard Deviation of sales: 10.0</pre><p>In simpler terms, <strong>the standard deviation tells us how much the data fluctuates or deviates from the mean.</strong></p><p>A <strong>higher standard deviation</strong> indicates that the data points are spread out widely from the mean, meaning there are more fluctuations and more unpredictable. A <strong>lower standard deviation</strong> indicates that the data points are close to the mean, meaning there’s less fluctuation and more stability for predictions.</p><p><strong>Scenario:</strong></p><p>You are analysing the <strong>click-through rates (CTR)</strong> for an online ad campaign across several days. The <strong>standard deviation</strong> will help you understand how much the performance varies from the average.</p><p>The goal is to understand how much <strong>variation</strong> exists in the performance of the campaign. A higher standard deviation indicates that the CTR is more volatile (i.e., it fluctuates widely), while a lower standard deviation shows consistent performance.</p><pre>import numpy as np<br><br># Dataset: CTR (Click-Through Rate) for an ad campaign over 7 days<br>ctr = [3.5, 4.0, 5.0, 2.5, 3.8, 4.2, 5.5]<br><br># Calculate mean (average) CTR<br>mean_ctr = np.mean(ctr)<br><br># Calculate standard deviation<br>std_dev_ctr = np.std(ctr)<br><br># Print results<br>print(&quot;Mean CTR:&quot;, round(mean_ctr,2))<br>print(&quot;Standard Deviation of CTR:&quot;, round(std_dev_ctr,2))<br>Mean CTR: 4.07<br>Standard Deviation of CTR: 0.91</pre><p>The <strong>average CTR</strong> is <strong>4.0%</strong> over the 7 days, meaning, on average, the ad campaign generated a 4% click-through rate. The <strong>standard deviation</strong> is <strong>0.93%</strong>. This means that, on average, the CTR deviates by about <strong>0.93%</strong> from the mean (4.0%). The<strong> low standard deviation</strong> (in this case) suggests that the CTR values are <strong>relatively consistent</strong> over the 7 days. There’s not much fluctuation, meaning the campaign’s performance is stable.</p><p><strong>3. Variance</strong></p><p>The third measure of the spread in a dataset is the <strong>variance</strong>. It is the <strong>average squared difference</strong> of each data point from the <strong>mean</strong> of the dataset and it is just the squared standard deviation. Since it is in squared units, it’s less intuitive to interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*rqVMIpoSYGQZNrvJbcNtaw.png" /></figure><pre>import numpy as np<br><br># Dataset: Daily revenue (in dollars)<br>daily_revenue = [500, 450, 600, 550, 700, 650, 750]<br><br># Calculate mean revenue<br>mean_revenue = np.mean(daily_revenue)<br><br># Calculate variance<br>variance_revenue = np.var(daily_revenue, ddof=1)  # ddof=1 for sample variance<br><br># Calculate standard deviation<br>std_dev_revenue = np.sqrt(variance_revenue)<br><br># Print results<br>print(&quot;Mean Revenue:&quot;, mean_revenue)<br>print(&quot;Variance of Revenue:&quot;, variance_revenue)<br>print(&quot;Standard Deviation of Revenue:&quot;, std_dev_revenue)<br>Mean Revenue: 600.0<br>Variance of Revenue: 11666.666666666666<br>Standard Deviation of Revenue: 108.01234497346434</pre><p><strong>When using variance instead of standard deviation?</strong></p><p>Both <strong>variance</strong> and <strong>standard deviation</strong> are measures of <strong>spread</strong> or <strong>dispersion</strong> in a dataset. They help you understand how much the data points deviate (or differ) from the <strong>mean</strong> (average).</p><p>So we use variance to <strong>calculate further statistical measures</strong> or to perform <strong>statistical analysis</strong> (e.g., regression analysis, hypothesis testing) etc.</p><p>Quick overview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Avgr41S7hDA_vxw6x-uGA.png" /></figure><p><strong>Variance in Hypothesis Testing:</strong></p><p>Variance helps determine if differences between groups (e.g., marketing strategies) are statistically significant. A high variance makes it harder to detect differences, while a low variance makes it easier.</p><p><strong>Variance in T-Test</strong>: The t-test compares the means of two groups and uses variance to calculate the standard error, which helps determine if the difference in means is statistically significant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*xhCW6yGsv5d29Rbg_mGBAQ.png" /></figure><p><strong>Variance in ANOVA</strong>: ANOVA compares the means of multiple groups and uses variance to test whether the differences between group means are larger than the variance within the groups (residual variance).</p><p>So in conclusion:</p><p>If the <strong>variance is high</strong> in either group, it means there’s a lot of <strong>spread</strong> in the data, making it harder to detect a <strong>significant difference</strong>. If the <strong>variance is low</strong>, the data points are <strong>closer to the average</strong>, which makes it easier to detect a significant difference between the two groups. By considering variance, you can assess if any differences observed are statistically meaningful or just due to random chance.</p><p>If the <strong>t-test</strong> gives a significant result (p-value &lt; 0.05), you might reject the null hypothesis and conclude that the marketing strategies lead to different sales outcomes. The <strong>variance</strong> tells you how much the sales data fluctuates, influencing the statistical test and your confidence in the results.</p><p><strong>Variance in Linear Regression:</strong></p><p>Variance helps explain how much of the variation in the dependent variable (e.g., sales) is explained by the independent variables (e.g., marketing spending). A low residual variance indicates a good model fit, while a high residual variance means the model doesn’t explain the data well.</p><p>R² measures the proportion of total variance in the dependent variable that is explained by the independent variables in the regression model. It indicates how well the independent variables explain the variation in the dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOTiPjCToMeN3sTanQLtqA.png" /></figure><p>A high <strong>R-squared</strong> value means that a large portion of the variance (or fluctuations) in sales can be explained by marketing spend and ad impressions for example.</p><p>A low <strong>R-squared</strong> means that marketing spending and ad impressions don’t explain much of the variation in sales, suggesting other factors might be more important.</p><p>So the <strong>variance</strong> in a dataset tells us how far or spread out the data is from the mean. It’s a <strong>general measure of variation</strong>. While the <strong>explained variance</strong> tells us how much of the <strong>spread (variance)</strong> in the data can be <strong>explained</strong> by the independent variables in your model. It shows us what factors (e.g., marketing spending) are <strong>correlated</strong> with the variability in the data.</p><p><strong>Variance in Confidence Intervals</strong></p><p>Briefly, a <strong>confidence interval</strong> gives us a range within which we are confident the true value of a parameter (like the average) lies. In this case, v<strong>ariance</strong> is used to calculate how wide or narrow this interval is.</p><p><strong>Higher variance</strong> = <strong>wider confidence interval</strong>: More spread out data means less precision in estimating the true value. <strong>Lower variance</strong> = <strong>narrower confidence interval</strong>: Less spread out data means more precision.</p><p><strong>4. Interquartile Range (IQR)</strong></p><p>The last measure of variability in the data is the <strong>IQR</strong> or Interquartile Range. It describes the spread of the middle 50% of the data, meaning it measures the “spread” of the middle of your data, ignoring the very low and very high values. The IQR is the difference between Q3 and Q1. IQR gives a reliable idea of the variability for skewed or non-normal data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*TVXTiA_wFaMBD1h-aiHd8w.png" /></figure><p>where Q1 is the first 25% percentile (the value below which 25% of the data falls) and Q3 is the 75% percentile (the value below which 75% of the data falls).</p><p>How to calculate Q1 and Q3?</p><ul><li>Sort the data</li><li>Find the median Q2</li><li>Consider the lower half of the data (excluding the median if there’s an odd number of data points) and find the median of this lower half. This is Q1.</li><li>Consider the upper half of the data (excluding the median if there’s an odd number of data points) and find the median of this upper half. This is Q3.</li></ul><p>or</p><pre>import numpy as np<br><br># Sample data<br>data = [3, 7, 8, 12, 13, 14, 18, 22, 24, 25, 26, 30, 31, 34, 36]<br><br># Calculate Q1 and Q3<br>Q1 = np.percentile(data, 25)<br>Q3 = np.percentile(data, 75)<br>print(&quot;Q1 is :&quot;, Q1)<br>print(&quot;Q3 is :&quot;, Q3)<br>Q1 is : 12.5<br>Q3 is : 28.0 </pre><p>The difference between the range and interquartile range is that the first one is sensitive to the outliers since it is the difference between the <strong>maximum</strong> and <strong>minimum</strong> values in the dataset, while the IQR is based on the <strong>quartiles</strong> and focuses on the middle 50% of the data. It’s <strong>less influenced by outliers</strong> compared to the range because it only considers the central values (Q1 to Q3).</p><p>So you can use <strong>IQR</strong> when you want to focus on the central spread and ignore outliers while you can use <strong>Range</strong> when you need the full extent of the data, including extremes.</p><p>So why don’t we just use Q1 and Q3 to determine the range?</p><p>While you <strong>can </strong>look at <strong>Q1</strong> (25th percentile) and <strong>Q3</strong> (75th percentile) individually, they provide <strong>different insights</strong> compared to the <strong>Interquartile Range (IQR)</strong>.</p><p><strong>The Q1 (25th percentile)</strong> is the <strong>value</strong> below which <strong>25%</strong> of the data lies. It gives an idea of where the <strong>lower quarter</strong> of your data falls. In marketing, this could represent the <strong>lower-performing 25%</strong> of campaigns or customers. The <strong>Q3 (75th percentile)</strong> is the <strong>value</strong> below which <strong>75%</strong> of the data lies. It provides insight into where the <strong>upper quarter</strong> of your data lies. For example, this might represent the <strong>top 25%</strong> of your customers or campaigns performing at a higher level. However, <strong>just knowing Q1 and Q3</strong> doesn’t tell you <strong>how spread out</strong> the middle 50% of the data is. This is where the <strong>IQR</strong> comes in.</p><p>The <strong>IQR</strong> is simply the <strong>difference</strong> between Q3 and Q1:</p><p>This value <strong>measures</strong> how <strong>spread out</strong> the middle 50% of your data is, and it <strong>ignores outliers</strong> (extreme values outside the 25th and 75th percentiles). <strong>Q1 and Q3</strong> tell you about the <strong>values at specific percentiles</strong> but don’t directly show you how <strong>spread out</strong> the middle part of your data is.</p><p>The <strong>IQR</strong>, on the other hand, specifically tells you the <strong>range</strong> where the <strong>middle 50% of the data</strong> lies, and <strong>how tightly or widely</strong> that part of the data is distributed.</p><ul><li><strong>Q1</strong> and <strong>Q3</strong> tell you about the <strong>position</strong> of data in the lower and upper quartiles but don’t directly show you how <strong>spread out</strong> that middle part of the data is.</li><li>The <strong>IQR</strong> gives you a <strong>measure of spread</strong> by calculating the distance between Q1 and Q3, allowing you to understand the <strong>variability</strong> within the middle 50% of your data.</li></ul><p>In marketing, knowing the <strong>IQR</strong> is useful for understanding the <strong>consistency</strong> of results (like sales or customer satisfaction) and identifying how spread out the central data is. Using just <strong>Q1 and Q3</strong> would give you a sense of where the data is located, but the <strong>IQR</strong> gives you a much more practical measure of spread.</p><p><strong>Scenario:</strong></p><p>A company wants to understand the spending patterns of its customers. While the range provides the full spread of spending (from the lowest to the highest purchase), the company uses the <strong>IQR</strong> to focus on the middle 50% of customer spending, ignoring extreme outliers like exceptionally high or low spenders.</p><pre>import numpy as np<br><br># Customer spending data in dollars<br>customer_spending = [20, 25, 30, 32, 35, 40, 45, 50, 55, 60, 65, 300]<br><br># Calculate Q1 and Q3<br>Q1 = np.percentile(customer_spending, 25)  # 25th percentile<br>Q3 = np.percentile(customer_spending, 75)  # 75th percentile<br><br># Calculate IQR<br>IQR = Q3 - Q1<br><br># Print the results<br>print(&quot;First Quartile (Q1):&quot;, Q1)<br>print(&quot;Third Quartile (Q3):&quot;, Q3)<br>print(&quot;Interquartile Range (IQR):&quot;, IQR)<br>First Quartile (Q1): 31.5<br>Third Quartile (Q3): 56.25<br>Interquartile Range (IQR): 24.75</pre><p>How to interpret the results?</p><p>The 50% of customers spend in the range of 31.5 and 56.25 with a variability of 24.75, meaning there is a consistent spending behaviour considering the difference between the first part of the data and the third part of the data.</p><h3>3.Descriptive Analysis for Categorical Data</h3><p>Frequency Tables, Proportions, and Cross-Tabulations are methods to summarize categorical data.</p><p>1. <strong>Frequency Tables</strong></p><p>A <strong>frequency table</strong> shows how often each category appears in a dataset.</p><pre>import pandas as pd<br><br># Data: Customer product preferences<br>products = [&#39;Shirt&#39;, &#39;Pants&#39;, &#39;Shirt&#39;, &#39;Shirt&#39;, &#39;Shoes&#39;, &#39;Pants&#39;, &#39;Shoes&#39;, &#39;Shirt&#39;]<br><br># Create a frequency table<br>frequency_table = pd.Series(products).value_counts()<br>df = frequency_table.reset_index()<br><br># Rename columns for clarity<br>df.columns = [&#39;Product&#39;, &#39;Frequency&#39;]<br><br># Print the frequency table<br>print(df)<br> Product  Frequency<br>0   Shirt          4<br>1   Pants          2<br>2   Shoes          2</pre><p>A frequency table could be used to analyse which products are being purchased the most. For example, if you have data on customer purchases and run a frequency table, it could reveal that <strong>Shirts</strong> are the most popular product, while <strong>Shoes</strong> and <strong>Pants</strong> are bought less frequently. This insight can guide inventory management and sales strategies.</p><p><strong>2. Proportions</strong></p><p><strong>Proportions</strong> show the relative frequency of each category in the data, usually expressed as a percentage of the total. It helps to understand the share of each category within the dataset.</p><pre># Data: Customer product preferences<br>products = [&#39;Shirt&#39;, &#39;Pants&#39;, &#39;Shirt&#39;, &#39;Shirt&#39;, &#39;Shoes&#39;, &#39;Pants&#39;, &#39;Shoes&#39;, &#39;Shirt&#39;]<br><br># Calculate proportions<br>proportions = pd.Series(products).value_counts(normalize=True)<br><br># Print the proportions<br>print(proportions)<br>Shirt    0.5<br>Pants    0.25<br>Shoes    0.25</pre><p>In this case, the shirts have the highest %, meaning they are the most preferred item in the store. The proportion can help businesses decide which products to focus marketing efforts on.</p><p><strong>3. Cross-Tabulations (Contingency Tables)</strong></p><p>A <strong>cross-tabulation</strong> (or contingency table) is a way to analyse the relationship between two categorical variables. It shows how categories of one variable relate to categories of another variable.</p><pre># Data: Customer preferences by gender<br>data = {<br>    &#39;Gender&#39;: [&#39;Male&#39;, &#39;Female&#39;, &#39;Male&#39;, &#39;Female&#39;, &#39;Male&#39;, &#39;Female&#39;, &#39;Male&#39;, &#39;Female&#39;],<br>    &#39;Product Preference&#39;: [&#39;Shirt&#39;, &#39;Pants&#39;, &#39;Shoes&#39;, &#39;Shirt&#39;, &#39;Pants&#39;, &#39;Shoes&#39;, &#39;Shirt&#39;, &#39;Shirt&#39;]<br>}<br><br># Create a DataFrame<br>df = pd.DataFrame(data)<br><br># Create a cross-tabulation (contingency table)<br>cross_tab = pd.crosstab(df[&#39;Gender&#39;], df[&#39;Product Preference&#39;])<br><br># Print the cross-tabulation<br>print(cross_tab)<br>Product Preference  Pants  Shoes  Shirt<br>Gender                                 <br>Female                   1      1      2<br>Male                     1      1      2</pre><p>The cross-tabulation shows that both <strong>Males</strong> and <strong>Females</strong> prefer <strong>Shirts</strong> (2 for each), while <strong>Pants</strong> and <strong>Shoes</strong> have a more balanced preference across both genders. This can help you design marketing campaigns tailored to specific gender preferences, ensuring better engagement and targeting.</p><p>To sumup, these methods help simplify the process of analyzing categorical data, enabling businesses to gain actionable insights for decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA2CKboFgnwrKfZXFAzN9Q.png" /></figure><h3>4.Measure of Distribution</h3><p>When we plot our data they can show different shapes and consequential essential insights into how the data behaves.</p><p>The key characteristics are <strong>symmetry/skewness </strong>and <strong>kurtosis</strong>.</p><p>When the data are symmetrically distributed we can refer to a <strong>normal distribution.</strong></p><p>The normal distribution is symmetrical with a bell-shaped curve, most values cluster around the mean and the central tendency values (mean, median and mode are the same). Hence the data is balanced around the center. The normal distribution comes with the <strong>empiric rule </strong>thanks to<strong> </strong>we can determine the percentage of the data that deviates from the center and falls within certain intervals.</p><p>The key concepts are:</p><ul><li>~68% within 1 standard deviation.</li><li>~95% within 2 standard deviations.</li><li>~99.7% within 3 standard deviations.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy.stats import norm<br><br># Generate data for normal distribution<br>mean = 50<br>std_dev = 10<br>data = np.random.normal(loc=mean, scale=std_dev, size=1000)<br><br># Create a figure and axis for plotting<br>plt.figure(figsize=(10,6))<br><br># Plot the histogram of the data<br>sns.histplot(data, kde=True, stat=&quot;density&quot;, color=&quot;blue&quot;, bins=30, label=&quot;Data&quot;)<br><br># Add the normal distribution curve<br>x = np.linspace(mean - 4*std_dev, mean + 4*std_dev, 1000)<br>plt.plot(x, norm.pdf(x, mean, std_dev), color=&#39;red&#39;, label=&quot;Normal Distribution&quot;, lw=2)<br><br># Add lines for the Empirical Rule<br>plt.axvline(mean - std_dev, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=&quot;Mean - 1 STD (68%)&quot;)<br>plt.axvline(mean + std_dev, color=&#39;green&#39;, linestyle=&#39;--&#39;)<br><br>plt.axvline(mean - 2*std_dev, color=&#39;orange&#39;, linestyle=&#39;--&#39;, label=&quot;Mean - 2 STD (95%)&quot;)<br>plt.axvline(mean + 2*std_dev, color=&#39;orange&#39;, linestyle=&#39;--&#39;)<br><br>plt.axvline(mean - 3*std_dev, color=&#39;purple&#39;, linestyle=&#39;--&#39;, label=&quot;Mean - 3 STD (99.7%)&quot;)<br>plt.axvline(mean + 3*std_dev, color=&#39;purple&#39;, linestyle=&#39;--&#39;)<br><br># Add labels and legend<br>plt.title(&quot;Normal Distribution with Empirical Rule&quot;, fontsize=16)<br>plt.xlabel(&quot;Value&quot;, fontsize=12)<br>plt.ylabel(&quot;Density&quot;, fontsize=12)<br>plt.legend()<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*nsbwidpOJHlzFOblJd8hog.png" /></figure><p>In detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*zNbwlBzdDbGqHYq_VSzcRA.png" /></figure><p>So we know that:</p><ul><li>~68% within 1 standard deviation. The 68% is divided by the two tails, so 34% each tail.</li><li>~95% within 2 standard deviations. In this case, excluding the 68%, we will have 27% divided by the two tails so 13,5% each ((95–68)/2 = 13,5)</li><li>~99.7% within 3 standard deviations. In this case, excluding the 95%, we will have 4,7% divided by the two tails so 2,35% each ((99,7–95)/2 = 2,35)</li></ul><p>What does it mean, and what can we do with these numbers?</p><p><strong>Scenario:</strong></p><p>You’re a marketing analyst for an e-commerce platform, and you’re analysing the <strong>amount spent on the platform</strong> of <strong>1000 customers</strong>. You assume that the spending follows a normal distribution, with a mean of $50 and a standard deviation of $15.</p><p>Now, you want to understand:</p><ul><li>How much of the customer spending falls within a typical range (e.g., within one standard deviation of the mean).</li><li>How much falls above and below the average spending.</li></ul><p>Marketing Questions:</p><p><strong>“What percentage of customers spend less than $35?”</strong></p><p><strong>“What percentage of customers spend more than $65?”</strong></p><p>As we know, the standard deviation tells us the amount of fluctuation, so the range between 35$ (50–15) and 65$ (50+15).</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy.stats import norm<br><br># Marketing data: Customer spending in dollars<br>mean = 50  # Mean spending<br>std_dev = 15  # Standard deviation of spending<br><br># Generate data for 1000 customers<br>data = np.random.normal(loc=mean, scale=std_dev, size=1000)<br><br># Create a figure and axis for plotting<br>plt.figure(figsize=(10,6))<br><br># Plot the histogram of the data<br>sns.histplot(data, kde=True, stat=&quot;density&quot;, color=&quot;blue&quot;, bins=30, label=&quot;Customer Spending&quot;)<br><br># Add the normal distribution curve<br>x = np.linspace(mean - 4*std_dev, mean + 4*std_dev, 1000)<br>plt.plot(x, norm.pdf(x, mean, std_dev), color=&#39;red&#39;, label=&quot;Normal Distribution&quot;, lw=2)<br><br># Calculate the probability of spending less than $35<br>prob_less_35 = norm.cdf(35, mean, std_dev)<br>prob_more_65 = 1 - norm.cdf(65, mean, std_dev)<br><br># Highlight the area where spending is less than $35 (left side)<br>x_fill_1 = np.linspace(mean - 4*std_dev, 35, 500)<br>plt.fill_between(x_fill_1, norm.pdf(x_fill_1, mean, std_dev), color=&#39;blue&#39;, alpha=0.3)<br><br># Highlight the area where spending is more than $65 (right side)<br>x_fill_2 = np.linspace(65, mean + 4*std_dev, 500)<br>plt.fill_between(x_fill_2, norm.pdf(x_fill_2, mean, std_dev), color=&#39;red&#39;, alpha=0.3)<br><br># Add labels and title<br>plt.title(&quot;Normal Distribution of Customer Spending&quot;, fontsize=16)<br>plt.xlabel(&quot;Spending in Dollars&quot;, fontsize=12)<br>plt.ylabel(&quot;Density&quot;, fontsize=12)<br><br># Annotate the percentage areas<br>plt.text(20, 0.02, f&quot;Less than $35\n{prob_less_35*100:.2f}%&quot;, fontsize=12, color=&quot;blue&quot;)<br>plt.text(75, 0.02, f&quot;More than $65\n{prob_more_65*100:.2f}%&quot;, fontsize=12, color=&quot;red&quot;)<br><br># Add legend<br>plt.legend()<br><br># Show the plot<br>plt.show()<br><br># Print the probability results<br>print(f&quot;Percentage of customers spending less than $35: {prob_less_35 * 100:.2f}%&quot;)<br>print(f&quot;Percentage of customers spending more than $65: {prob_more_65 * 100:.2f}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*QgVOCoET4OzkqrN4NR8zPg.png" /></figure><p>Why 15,87%?</p><p>Applying the empiric rule we know that 68% of the data fall within 1 standard deviation. In this case, we want to know the remaining area outside the 68%. So 99,7% (the entire area excluding the 0,3 of outliers) — 68% of data fall into 1 standard deviation we have 31,7% divided by the two tails meaning 15,87%.</p><p>In most cases, we are not so lucky and the data doesn’t follow a normal distribution. In this case, we talk about <strong>skewness</strong>, a<strong> </strong>measure of asymmetry.<strong> </strong>There are two types of skewness:</p><ul><li><strong>right-skewness (or positive skewness):</strong> the tail is on the right while the majority of the data is concentrated on the left side of the graph.</li></ul><pre>data_skewed_right = np.random.exponential(scale=10, size=1000)<br><br># Plot histogram<br>plt.hist(data_skewed_right, bins=30, density=True, alpha=0.6, color=&#39;salmon&#39;, edgecolor=&#39;black&#39;)<br>plt.title(&quot;Right-Skewed Distribution&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*iHGgT_Nv5aVxyO41BDZ3ow.png" /></figure><p><strong>Scenario:</strong></p><p>You’re a <strong>marketing analyst</strong> for an online retail store. You’re analysing the <strong>purchase amounts</strong> of a large number of customers. Most customers make small purchases, but a few customers make large purchases. You want to understand the distribution of customer spending.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import skewnorm<br><br># Parameters for the right-skewed distribution<br>alpha = 5  # Positive value indicates right skew<br>size = 1000  # Sample size representing 1000 customers<br><br># Generate a right-skewed distribution using skewnorm<br>customer_spending = skewnorm.rvs(alpha, loc=50, scale=20, size=size)  # Mean of 50, SD of 20<br><br># Calculate mean and median<br>mean_spending = np.mean(customer_spending)<br>median_spending = np.median(customer_spending)<br><br>#skewness<br>skewness = skew(customer_spending)<br><br><br># Plot the histogram<br>plt.hist(customer_spending, bins=30, color=&#39;skyblue&#39;, edgecolor=&#39;black&#39;, alpha=0.7)<br>plt.axvline(mean_spending, color=&#39;red&#39;, linestyle=&#39;dashed&#39;, linewidth=2, label=f&#39;Mean: {mean_spending:.2f}&#39;)<br>plt.axvline(median_spending, color=&#39;green&#39;, linestyle=&#39;dashed&#39;, linewidth=2, label=f&#39;Median: {median_spending:.2f}&#39;)<br>plt.title(&#39;Right-Skewed Customer Spending Distribution&#39;)<br>plt.xlabel(&#39;Spending Amount ($)&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.legend()<br>plt.show()<br><br># Output mean and median<br>print(f&quot;Mean Spending: ${mean_spending:.2f}&quot;)<br>print(f&quot;Median Spending: ${median_spending:.2f}&quot;)<br># Output skewness<br>print(f&quot;Skewness: {skewness:.2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*SUmoWRPJHBZAxorkVBgrYA.png" /></figure><p>How to interpret this graph?</p><p>Most customers are low spenders, while a few are high spenders.</p><ul><li><strong>left- skewness (or negative skewness):</strong> the tail is on the left while the majority of the data is concentrated on the right side of the graph.</li></ul><pre>data_skewed_left = -1 * np.random.exponential(scale=10, size=1000)<br><br># Plot histogram<br>plt.hist(data_skewed_left, bins=30, density=True, alpha=0.6, color=&#39;lightgreen&#39;, edgecolor=&#39;black&#39;)<br>plt.title(&quot;Left-Skewed Distribution&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*CaQiRfBfdlXI00AQwwApyg.png" /></figure><p><strong>Scenario:</strong></p><p>You’re a <strong>marketing analyst</strong> for a subscription-based platform offering premium and basic plans. After running a promotion, you analyse the <strong>subscription durations</strong> (in months) to see how long customers typically stay subscribed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*3PQSUEMmnmINPKqumzm5nw.png" /></figure><p>Most customers sign up for <strong>long durations</strong> (e.g., annual plans), but a few subscribe for shorter periods (e.g., 1 or 2 months). This creates a <strong>left-skewed distribution</strong>.</p><p>The last element is<strong> kurtosis </strong>which measures the “tailedness” of the dataset meaning how much data is located in the tails and the sharpness of the peak. A <strong>high kurtosis </strong>means more frequent extreme values while <strong>low kurtosis </strong>means fewer<strong> </strong>extreme values.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import kurtosis<br><br># Generating data<br>np.random.seed(42)<br><br># Mesokurtic (Normal Distribution)<br>normal_data = np.random.normal(loc=50, scale=10, size=1000)<br><br># Leptokurtic (High Kurtosis)<br>leptokurtic_data = np.random.laplace(loc=50, scale=10, size=1000)<br><br># Platykurtic (Low Kurtosis)<br>platykurtic_data = np.random.uniform(low=30, high=70, size=1000)<br><br># Calculate Kurtosis<br>normal_kurt = kurtosis(normal_data, fisher=False)<br>lepto_kurt = kurtosis(leptokurtic_data, fisher=False)<br>platy_kurt = kurtosis(platykurtic_data, fisher=False)<br><br># Plotting<br>data_sets = [normal_data, leptokurtic_data, platykurtic_data]<br>titles = [<br>    f&quot;Mesokurtic (Kurtosis: {normal_kurt:.2f})&quot;,<br>    f&quot;Leptokurtic (Kurtosis: {lepto_kurt:.2f})&quot;,<br>    f&quot;Platykurtic (Kurtosis: {platy_kurt:.2f})&quot;<br>]<br><br>plt.figure(figsize=(15, 5))<br>for i, data in enumerate(data_sets):<br>    plt.subplot(1, 3, i + 1)<br>    plt.hist(data, bins=30, color=&#39;skyblue&#39;, edgecolor=&#39;black&#39;, alpha=0.7)<br>    plt.title(titles[i])<br>    plt.xlabel(&#39;Value&#39;)<br>    plt.ylabel(&#39;Frequency&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*Z5yQ2dPDfnTurxORjivU4g.png" /></figure><p><strong>Kurtosis examples:</strong></p><p><strong>Leptokurtic Distribution:</strong></p><p>Analyse spending during special promotions or events, where a few customers might make unusually large purchases.</p><p><strong>Platykurtic Distribution:</strong></p><p>Understand sales consistency across regions or products with uniform demand.</p><p><strong>Mesokurtic Distribution:</strong></p><p>Analyse regular spending patterns in a store to understand typical customer behaviour.</p><p>As we saw for skewness, we can determine the kurtosis with a value:</p><ol><li><strong>Mesokurtic (Normal Kurtosis): Kurtosis ≈ 3</strong> (excess kurtosis = 0)</li><li><strong>Leptokurtic (High Kurtosis): Kurtosis &gt; 3</strong> (excess kurtosis &gt; 0)</li><li><strong>Platykurtic (Low Kurtosis): Kurtosis &lt; 3</strong> (excess kurtosis &lt; 0)</li></ol><p>To sumup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*Qr1Me6cuqkNPSiT_1lOODA.png" /></figure><h3>5. Data Visualization</h3><p>The last part is related to how to visualize the data, although we have already had an introduction through the article. Data visualization is crucial for understanding patterns, trends, and relationships within the data.</p><p>Some of the most popular are:</p><ul><li>histograms</li><li>box plots</li><li>scatterplots</li><li>density plots</li><li>heatmap</li></ul><h4><strong>Histograms</strong></h4><p>Histograms display the frequency distribution of numerical data, aiding in understanding the data’s shape and spread. It divides the data into intervals (bins) and plots the number of data points in each bin.</p><p><strong>How to interpret</strong>:</p><ul><li>The <strong>x-axis</strong> represents the data values (e.g., customer ages).</li><li>The <strong>y-axis</strong> represents the frequency or count of occurrences within each interval.</li><li><strong>Shape</strong>: Observe the shape of the histogram. A <strong>normal distribution</strong> will form a bell curve, whereas a <strong>skewed distribution</strong> will show a tail to the left or right.</li><li><strong>Spread</strong>: The width of the bins and how spread out the data is. Wide bins indicate more variability.</li><li><strong>Peaks</strong>: Indicate the most common values.</li></ul><p><strong>Scenario:</strong></p><p>A histogram of <strong>customer age groups</strong> can help you identify which age groups dominate your customer base. This can inform targeted marketing strategies.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br># Simulate customer age data (e.g., ages from 18 to 70)<br>np.random.seed(42)<br>customer_ages = np.random.randint(18, 70, size=500)<br># Create histogram<br>plt.figure(figsize=(8, 6))<br>plt.hist(customer_ages, bins=10, color=&#39;skyblue&#39;, edgecolor=&#39;black&#39;)<br>plt.title(&quot;Histogram of Customer Ages&quot;)<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*xcs3VisumS-U-YBJ9Jqpwg.png" /></figure><p>In this case, the customer base doesn’t show any particular peak across the range and the histogram shows an approximately uniform distribution. We may need broad marketing strategies targeting all age groups rather than focusing on a specific demographic.</p><h4>Box Plots</h4><p>The box plot (also known as <strong>box-and-whisker plot</strong>) is a simple yet powerful way to visualize and summarize the dataset.</p><p>The key components are:</p><ul><li><strong>Q0 and Q4 (minimum and maximum values)</strong></li><li><strong>Q1 and Q3 (quartiles)</strong></li><li><strong>Median: </strong>the line inside the box representing the data&#39;s median (50th percentile).</li><li><strong>IQR:</strong> the box represents the <strong>interquartile range (IQR)</strong>, the range between Q1 and Q3, showing where the middle 50% of data lies</li><li><strong>Whiskers: </strong>lines extending from the box to the highest and lowest values within 1.5 times the IQR from the quartiles (Q1 and Q3). They show the spread of data within a typical range (excluding outliers). The lower whisker is the smallest value within the acceptable range (1.5 * IQR below Q1), while the upper whisker is the largest value within the acceptable range (1.5 * IQR above Q3).</li><li><strong>Outliers: </strong>data points outside of the whiskers, often shown as dots or asterisks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*SaQNv2EMLAe2Ksjgbw-8hA.png" /></figure><p>Besides the key components, this graph shows us the spread and the skewness of the dataset.</p><p><strong>How to read a box plot?</strong></p><ul><li>A wide <strong>box</strong> means a larger range of values in the middle 50%, while a narrow box means the data is more concentrated.</li><li>The <strong>median line </strong>inside the box tells you where the middle of the data lies. If the median is near the centre of the box, the data is relatively symmetrically distributed. If it’s closer to one end, the data may be skewed.</li><li>If the <strong>whiskers</strong> are longer on one side of the box, the data is <strong>skewed</strong>. A longer whisker on the right suggests <strong>positive skewness</strong> (data is spread out to the right), and a longer whisker on the left suggests <strong>negative skewness</strong> (data is spread out to the left).</li></ul><p>In detail, the position of the <strong>median</strong> (Q2) inside the <strong>box</strong> can give you an initial idea of whether the data is <strong>skewed</strong>. Specifically:</p><ul><li><strong>Symmetric Distribution</strong>: If the median is <strong>near the center</strong> of the box (equidistant from Q1 and Q3), it suggests that the data is <strong>approximately symmetric</strong>.</li><li><strong>Right-skewed (Positive Skew)</strong>: If the <strong>median</strong> is <strong>closer to Q1</strong> (left side of the box), this indicates that the data has a <strong>longer tail on the right</strong> (higher values).</li><li><strong>Left-skewed (Negative Skew)</strong>: If the <strong>median</strong> is <strong>closer to Q3</strong> (right side of the box), this suggests a <strong>longer tail on the left</strong> (lower values).</li></ul><p>Also, the <strong>whiskers</strong> in a box plot give insight into the <strong>skewness</strong> of the data:</p><ul><li><strong>Symmetric Data</strong>: If both whiskers (left and right) are <strong>about the same length</strong>, the data is symmetric.</li><li><strong>Right-skewed (Positive Skew)</strong>: If the <strong>right whisker</strong> (on the higher end of the data) is <strong>longer</strong> than the <strong>left whisker</strong>, it suggests a <strong>right-skewed</strong> distribution (data is stretched toward higher values).</li><li><strong>Left-skewed (Negative Skew)</strong>: If the <strong>left whisker</strong> is <strong>longer</strong> than the right whisker, the data is <strong>left-skewed</strong> (data is stretched toward lower values).</li></ul><p>It’s possible for the median to be close to Q1 (indicating a potential right-skewed distribution), while the left whisker is longer or vice versa. This can happen in certain cases where the distribution is not perfectly skewed in a typical manner, or if outliers are affecting the whiskers.</p><p>What Could Cause This?</p><ol><li><strong>Outliers:</strong></li></ol><p>Outliers or extreme values on the left-hand side of the distribution can stretch the left whisker, even when the median is closer to Q1. This could happen if there are a few unusually low values, which would pull the left whisker longer.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Generate random data for each distribution<br><br># 1. Normal Distribution<br>normal_data = np.random.normal(loc=50, scale=15, size=1000)  # mean=50, std=15<br><br># 2. Right Skewed Distribution<br>right_skewed_data = np.random.beta(a=2, b=5, size=1000) * 50 + 25  # Right skewed<br><br># 3. Left Skewed Distribution<br>left_skewed_data = np.random.beta(a=5, b=2, size=1000) * 50 + 25  # Left skewed<br><br># Create a figure with multiple subplots<br>plt.figure(figsize=(12, 8))<br><br># Plot the boxplot for normal distribution<br>plt.subplot(131)<br>sns.boxplot(data=normal_data, color=&#39;skyblue&#39;)<br>plt.title(&#39;Normal Distribution&#39;)<br><br># Plot the boxplot for right skewed distribution<br>plt.subplot(132)<br>sns.boxplot(data=right_skewed_data, color=&#39;lightgreen&#39;)<br>plt.title(&#39;Right Skewed Distribution&#39;)<br><br># Plot the boxplot for left skewed distribution<br>plt.subplot(133)<br>sns.boxplot(data=left_skewed_data, color=&#39;lightcoral&#39;)<br>plt.title(&#39;Left Skewed Distribution&#39;)<br><br># Display the plots<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*vIiyfwXvXvhC9gNjzS12TQ.png" /></figure><p>Let’s see with a real-case scenario!</p><p><strong>Scenario:</strong></p><p>You’re a marketing analyst for an e-commerce platform, and you want to compare <strong>satisfaction scores</strong> for different products. This shows the spread of customer feedback and highlights any extreme ratings.</p><pre># Simulate satisfaction scores for different products<br>np.random.seed(42)<br>product_a = np.random.normal(loc=75, scale=10, size=100)<br>product_b = np.random.normal(loc=80, scale=15, size=100)<br>product_c = np.random.normal(loc=70, scale=5, size=100)<br># Create a DataFrame for plotting<br>import pandas as pd<br>df = pd.DataFrame({<br>    &quot;Product A&quot;: product_a,<br>    &quot;Product B&quot;: product_b,<br>    &quot;Product C&quot;: product_c<br>})<br># Create box plot<br>plt.figure(figsize=(8, 6))<br>sns.boxplot(data=df)<br>plt.title(&quot;Box Plot of Product Satisfaction Scores&quot;)<br>plt.xlabel(&quot;Products&quot;)<br>plt.ylabel(&quot;Satisfaction Score&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*mL8zXuRnDhLTiOypI1mZtA.png" /></figure><p>How to interpret it?</p><p>1. <strong>Central Tendency (Median):</strong></p><ul><li><strong>Product A</strong>: The median satisfaction score is around 75.</li><li><strong>Product B</strong>: The median satisfaction score is higher than Product A, approximately 80.</li><li><strong>Product C</strong>: The median satisfaction score is lower, around 70.</li><li><strong>Interpretation</strong>: Product B has the highest central satisfaction score, while Product C has the lowest.</li></ul><p><strong>2. Spread (Interquartile Range — IQR):</strong></p><ul><li><strong>Product A</strong>: The IQR (difference between Q3 and Q1) is relatively narrow, indicating less variability in satisfaction scores.</li><li><strong>Product B</strong>: The IQR is the widest, showing greater variability in customer satisfaction compared to the other two products.</li><li><strong>Product C</strong>: The IQR is the narrowest, showing the least variability in satisfaction.</li><li><strong>Interpretation</strong>: Product C has more consistent satisfaction levels, while Product B experiences the most variability.</li></ul><p><strong>3. Outliers:</strong></p><ul><li><strong>Product A</strong>: There is one outlier below the whisker (~50), representing a highly dissatisfied customer.</li><li><strong>Product B</strong>: There is one outlier above the whisker (~120), showing an extremely satisfied customer.</li><li><strong>Product C</strong>: There is one outlier below the whisker (~55), indicating a very dissatisfied customer.</li><li><strong>Interpretation</strong>: Outliers in each product indicate exceptional cases of customer experiences, either extremely good or bad.</li></ul><p><strong>4. Range (Whiskers):</strong></p><ul><li><strong>Product A</strong>: Satisfaction scores range from about 55 to 90.</li><li><strong>Product B</strong>: Satisfaction scores range from about 50 to 115.</li><li><strong>Product C</strong>: Satisfaction scores range from about 60 to 75.</li><li><strong>Interpretation</strong>: Product B has the widest overall range, indicating the most diverse customer satisfaction experiences.</li></ul><p><strong>5. Relative Comparison:</strong></p><ul><li><strong>Consistency</strong>: Product C is the most consistent in satisfaction scores, with a narrow IQR and smaller range.</li><li><strong>Customer Sentiment</strong>: Product B has the highest median satisfaction but also shows more variability and extreme outliers, indicating a mixed experience among customers.</li><li><strong>Areas for Improvement</strong>: Product A has a relatively smaller range of scores but includes a dissatisfied customer (outlier), suggesting the need to address specific cases of dissatisfaction.</li></ul><p><strong>Key Insights:</strong></p><ul><li><strong>Product B</strong> performs best overall (highest median) but has the most inconsistent satisfaction.</li><li><strong>Product C</strong> shows consistent satisfaction but could improve its median satisfaction score to compete with Product A and B.</li><li><strong>Product A</strong> has moderate performance but should focus on addressing the dissatisfaction indicated by the outlier.</li></ul><h3>Scatter Plots</h3><p><strong>Scatter plots</strong> show the relationship between two <strong>numerical variables</strong> by plotting data points on a 2D graph. An important aspect is the <strong>correlation coefficient (r)</strong> which quantifies the strength and direction of the relationship between the two variables. The value of <strong>r</strong> ranges from -1 to 1:</p><ul><li><strong>r = 1</strong>: Perfect positive correlation (as one variable increases, the other increases).</li><li><strong>r = -1</strong>: Perfect negative correlation (as one variable increases, the other decreases).</li><li><strong>r = 0</strong>: No correlation (there is no linear relationship between the variables).</li><li><strong>0.0 r ±0.2</strong>: Low correlation (positive or negative).</li><li><strong>±0.2 r ±0.5</strong>: Moderate correlation (positive or negative).</li><li><strong>±0.5 r ±1.0</strong>: Strong correlation (positive or negative).</li></ul><p><strong>How to interpret</strong>:</p><ul><li>Each <strong>point</strong> represents a data observation (e.g., one customer).</li><li>The <strong>x-axis</strong> and <strong>y-axis</strong> represent the two variables being compared (e.g., <strong>marketing spend</strong> vs. <strong>sales revenue</strong>).</li><li><strong>Trends, clusters or correlations</strong> can be identified, e.g., a positive correlation where higher spending results in higher sales.</li><li><strong>Outliers</strong>: Points far from the main cluster can indicate extreme values that might warrant further analysis.</li></ul><h4>Scenario:</h4><p>Imagine you are a marketing analyst and you want to see if there is a correlation or not between customer age and customer spending.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Simulate data (e.g., customer age and customer spending)<br>np.random.seed(42)<br>age = np.random.randint(18, 70, size=100)  # Age between 18 and 70<br>spending = 50 + age * 0.8 + np.random.normal(0, 10, size=100)  # Spending correlated with age<br><br># Scatter plot<br>plt.figure(figsize=(8, 6))<br>plt.scatter(age, spending, color=&#39;skyblue&#39;, edgecolor=&#39;black&#39;)<br>plt.title(&quot;Scatter Plot of Customer Age vs. Spending&quot;)<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Spending ($)&quot;)<br>plt.show()<br><br># Calculate the correlation coefficient (r)<br>correlation = np.corrcoef(age, spending)[0, 1]<br>print(&quot;Correlation coefficient (r):&quot;, correlation)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*RvUImxk79wqRAXJYasFc6Q.png" /></figure><p>In this case, the graph shows a strong positive correlation meaning that as the age increases, so the spending. So maybe the company could consider to tailor marketing strategies to age groups.</p><p><strong>Remember, correlation doesn’t mean causation!</strong></p><h4>Heatmaps</h4><p>Heatmaps visualize data density or correlation matrices (a table that displays the correlation coefficients between multiple variables in a dataset), often used to show engagement or interaction across segments. It is useful for exploring relationships between <strong>multiple variables</strong> or tracking <strong>user activity.</strong></p><p><strong>Key Components:</strong></p><ul><li><strong>Color Intensity</strong>: The color gradient represents values. Darker colours typically indicate higher values, while lighter colours indicate lower values.</li><li><strong>Axes</strong>: Can represent time periods, categories, or numerical ranges, depending on the context.</li><li><strong>Clusters</strong>: Look for groupings of high or low values to identify patterns in the data, such as times of high customer engagement.</li></ul><pre>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Generate random data for the heatmap (e.g., 10x10 grid of values)<br>data = np.random.rand(10, 10)<br><br># Create a heatmap<br>plt.figure(figsize=(8, 6))<br>sns.heatmap(data, annot=True, cmap=&#39;coolwarm&#39;, linewidths=0.5)<br>plt.title(&#39;Example Heatmap&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Nznp3E32BuWsVuGZpEAuug.png" /></figure><p><strong>Scenario:</strong></p><p>You are a marketing analyst and your company wants to understand the user activity (e.g., logins or interactions) at different times of the day. This will help marketers plan ads for maximum visibility.</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Simulated data: User activity across the hours of the day (0 to 23) for 7 days of the week<br>np.random.seed(42)<br>hours = np.arange(24)  # 0 to 23 hours<br>days = [&#39;Monday&#39;, &#39;Tuesday&#39;, &#39;Wednesday&#39;, &#39;Thursday&#39;, &#39;Friday&#39;, &#39;Saturday&#39;, &#39;Sunday&#39;]<br><br># Generate random user activity (values between 0 and 100)<br>activity_data = np.random.randint(0, 100, size=(7, 24))<br><br># Create a DataFrame for easy manipulation<br>df_activity = pd.DataFrame(activity_data, columns=hours, index=days)<br><br># Create a heatmap to visualize user activity<br>plt.figure(figsize=(10, 8))<br>sns.heatmap(df_activity, annot=True, cmap=&#39;YlGnBu&#39;, cbar_kws={&#39;label&#39;: &#39;User Activity&#39;}, linewidths=0.5)<br>plt.title(&#39;User Activity by Time of Day&#39;)<br>plt.xlabel(&#39;Hour of Day&#39;)<br>plt.ylabel(&#39;Day of the Week&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*gT0I4L4D4oZhOrtk41hczQ.png" /></figure><p><strong>Interpretation of the Heatmap:</strong></p><ul><li><strong>High Activity Zones</strong>: Areas, where the heatmap cells are coloured darker (representing higher activity), indicate times and days when users are most active.</li><li><strong>Low Activity Zones</strong>: Lighter areas indicate times when user activity is lower (e.g., late-night hours or mid-morning hours).</li><li><strong>Patterns</strong>: The heatmap allows marketers to identify trends such as peak user activity times during lunch hours, early mornings, or weekends.</li></ul><p><strong>Key takeaways:</strong></p><ul><li><strong>Peak Engagement Times</strong>: From the heatmap, marketers can identify the best times to run ads, such as during high-activity periods (e.g., 8–10 AM, 6–8 PM, or weekends). They can schedule ads for maximum impact.</li><li><strong>Optimizing Ad Placement</strong>: If the data shows that users are more active on certain days (e.g., weekends), then they can optimize the ad budget to focus on those days.</li></ul><h4>Density Plots</h4><p>The<strong> density plots</strong> represent the <strong>smoothed version</strong> of a histogram, showing the probability distribution of a continuous variable. It’s essentially a smoothed histogram, providing a more accurate representation of the underlying probability density function, meaning, that unlike histograms, which have discrete bins, density plots are smooth curves. This makes it easier to visualize the shape of the distribution.</p><ul><li><strong>How to interpret</strong>:</li><li>The <strong>x-axis</strong> represents the data range.</li><li>The <strong>y-axis</strong> represents the probability density.</li><li>Useful for identifying the <strong>prevalent range</strong> of values and for comparing different datasets.</li></ul><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br># Generate random data (e.g., customer spending data)<br>np.random.seed(42)<br>customer_spending = np.random.normal(loc=50, scale=15, size=1000)<br><br># Create a density plot<br>plt.figure(figsize=(8, 6))<br>sns.kdeplot(customer_spending, shade=True, color=&quot;blue&quot;, linewidth=2)<br><br># Add titles and labels<br>plt.title(&#39;Density Plot of Customer Spending&#39;)<br>plt.xlabel(&#39;Spending ($)&#39;)<br>plt.ylabel(&#39;Density&#39;)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*_90Zc3a3SMtsQB2e3wO0OA.png" /></figure><h4>Add interpretation</h4><p>To sumup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKTcafKlQxgG_Np_dyKCjQ.png" /></figure><h3>6. <strong>Challenges and Takeaways and applications</strong></h3><p><strong>Challenges:</strong></p><ol><li><strong>Data Quality and Cleanliness</strong>:</li></ol><p><strong>Missing Data</strong>: Descriptive statistics can be skewed or inaccurate when data is missing, and handling missing data appropriately (e.g., imputation, deletion) is crucial.</p><p><strong>Outliers</strong>: Extreme values or outliers can significantly impact measures like the mean and skew the interpretation of the data.</p><p><strong>Data Consistency</strong>: Inconsistent data (e.g., different units or formats) can lead to misleading conclusions if not standardized.</p><p>2.<strong> Misinterpretation of Summary Measures</strong>:</p><p><strong>Mean vs. Median</strong>: The mean can be misleading in the presence of outliers or skewed data. Relying on the median or other measures (like trimmed means) can often provide more reliable insights.</p><p><strong>Range and IQR</strong>: The range can be heavily influenced by outliers, while IQR offers a better representation of the spread of data in the middle 50%.</p><p>3.<strong> Choosing the Right Measure</strong>:</p><p><strong>Which Summary Statistic to Use</strong>: Depending on the distribution of the data (normal, skewed, etc.), selecting the right descriptive measure is critical for accurate analysis.</p><p><strong>Context Matters</strong>: What works for one context (e.g., income data) might not be appropriate for another (e.g., age data), so a deep understanding of the dataset and context is necessary.</p><p>4. <strong>Large Datasets</strong>:</p><p><strong>Computational Complexity</strong>: Handling very large datasets can require sophisticated software tools and more computational power, especially when calculating detailed descriptive statistics across multiple variables.</p><p><strong>Data Aggregation</strong>: For large datasets, summarizing at the right level of granularity (e.g., grouping by categories) without losing critical insights can be challenging.</p><p><strong>Key Takeaways:</strong></p><ol><li><strong>Descriptive Statistics Summarize Data</strong>:</li></ol><p>Descriptive statistics are the backbone of initial data analysis, providing quick insights into data distribution, central tendency, spread, and shape. Measures like mean, median, mode, range, variance, and standard deviation offer useful ways to summarize data.</p><p>2.<strong> Data Distribution is Key</strong>:</p><p>The <strong>shape</strong> of the data (e.g., normal, skewed, bimodal) should dictate the choice of statistical measures. For example, if the data is skewed, the median and IQR might be more reliable than the mean and standard deviation.</p><p>3. <strong>Visualizations are Crucial</strong>:</p><p>Visual representations, like histograms, box plots, and scatter plots, help in understanding the data quickly and allow for easier interpretation of descriptive statistics.</p><p>They can also help in identifying outliers, gaps, and patterns in the data that might not be immediately apparent from numerical statistics alone.</p><p><strong>3. Outliers Matter</strong>:</p><p>Outliers can significantly distort descriptive statistics like the mean and standard deviation. Identifying and deciding how to handle them (whether to remove or keep them) is crucial in obtaining meaningful insights.</p><p>Thanks for reading and hope to see you in the next chapter!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*4SLASmwf0It-eCgl.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32d70ab97741" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>