<?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"><channel><title><![CDATA[Does Price Drive Customer Satisfaction?]]></title><description><![CDATA[Does Price Drive Customer Satisfaction?]]></description><link>https://pric.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 20:28:32 GMT</lastBuildDate><atom:link href="https://pric.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[What 10,000 Sales Transactions Taught Me About Discounting, Profit and Regional Performance]]></title><description><![CDATA[As part of building my data analyst portfolio, I recently completed an end-to-end sales analysis project using Microsoft Excel, SQL, and Tableau. The…]]></description><link>https://pric.hashnode.dev/what-10-000-sales-transactions-taught-me-about-discounting-profit-and-regional-performance</link><guid isPermaLink="true">https://pric.hashnode.dev/what-10-000-sales-transactions-taught-me-about-discounting-profit-and-regional-performance</guid><dc:creator><![CDATA[Tee Wanjiru]]></dc:creator><pubDate>Tue, 21 Apr 2026 11:15:34 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>As part of building my data analyst portfolio, I recently completed an end-to-end sales analysis project using Microsoft Excel, SQL, and Tableau. The dataset — a US-based superstore with over 10,000 orders spanning four years — gave me a realistic business scenario to work through: understanding what is driving revenue, what is hurting profitability, and what a business should do differently.</p>
<p>This article walks through my process, my findings, and the recommendations I would make if this were a real client engagement.</p>
<h2>The Dataset</h2>
<p>The Sample Superstore dataset contains 10,194 rows of order data covering January 2023 to December 2026. Each row represents a single product sold within an order, with fields for the customer, region, product category, sales amount, quantity, discount applied, and profit generated.</p>
<p>Before any analysis, I ran a basic data quality check:</p>
<ul>
<li><p>No duplicate rows found</p>
</li>
<li><p>No null values in any column</p>
</li>
<li><p>Category names were consistent across all rows</p>
</li>
</ul>
<p>The data was clean enough to work with after adding two calculated columns:</p>
<ul>
<li><p><strong>Profit Margin %</strong> — to measure how efficiently each sale converts to profit</p>
</li>
<li><p><strong>Revenue per Order</strong> — to understand the average value being generated per transaction</p>
</li>
</ul>
<hr />
<h2>Tools Used</h2>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Microsoft Excel</td>
<td>Data cleaning, calculated columns, pivot tables, dashboard</td>
</tr>
<tr>
<td>SQL (SQLite via DB Browser)</td>
<td>Business question analysis, window functions, CTEs</td>
</tr>
<tr>
<td>Tableau Public</td>
<td>Interactive visualisations and final dashboard</td>
</tr>
</tbody></table>
<hr />
<h2>Excel: Cleaning and Exploring the Data</h2>
<p>The first step was loading the raw data into Excel and getting familiar with it. I used pivot tables to slice the data across three dimensions:</p>
<p><strong>Pivot 1 — Sales &amp; Profit by Region</strong> A simple aggregation showing that the West region leads in both total sales (\(739,814) and total profit (\)110,799), while the Central region has the weakest profit margin despite ranking third in sales volume.</p>
<p><strong>Pivot 2 — Top 10 Sub-Categories by Profit</strong> Sorted descending by profit, this pivot immediately surfaced Copiers as the standout performer at $56,094 in profit, while also hinting at which sub-categories were underperforming.</p>
<p><strong>Pivot 3 — Monthly Sales Trend</strong> Grouping order dates by Year and Month revealed a recurring seasonal pattern — something I would later confirm with SQL.</p>
<h2>SQL: Answering the Business Questions</h2>
<p>After cleaning the data in Excel, I imported the Orders sheet into SQLite as a CSV and wrote nine queries to answer specific business questions. Here are the most interesting ones.</p>
<hr />
<h3>Which sub-categories are losing money?</h3>
<pre><code class="language-sql">SELECT 
    `Sub-Category`,
    Category,
    ROUND(SUM(Profit), 2) AS Total_Profit,
    ROUND(SUM(Sales), 2) AS Total_Sales
FROM orders
GROUP BY `Sub-Category`, Category
HAVING SUM(Profit) &lt; 0
ORDER BY Total_Profit ASC;
</code></pre>
<p><strong>Result:</strong> Three sub-categories generated negative profit across the entire four-year period — Tables, Bookcases, and Supplies. All three sit within the Furniture category.</p>
<pre><code class="language-sql">SELECT 
    CASE 
        WHEN Discount = 0 THEN '0% - No Discount'
        WHEN Discount &lt;= 0.2 THEN '1% - 20%'
        WHEN Discount &lt;= 0.4 THEN '21% - 40%'
        ELSE 'Above 40%'
    END AS Discount_Bracket,
    COUNT(*) AS Total_Orders,
    ROUND(AVG(Profit), 2) AS Avg_Profit,
    ROUND(AVG(Sales), 2) AS Avg_Sales
FROM orders
GROUP BY Discount_Bracket
ORDER BY Avg_Profit DESC;
</code></pre>
<p><strong>Result:</strong> Average profit is highest when no discount is applied and turns negative once discounts exceed 20%. This is one of the most actionable findings in the entire project.</p>
<hr />
<h3>Who are the top customers by revenue?</h3>
<pre><code class="language-sql">SELECT 
    `Customer Name`,
    ROUND(SUM(Sales), 2) AS Total_Revenue,
    COUNT(DISTINCT `Order ID`) AS Total_Orders
FROM orders
GROUP BY `Customer Name`
ORDER BY Total_Revenue DESC
LIMIT 10;
</code></pre>
<p><strong>Result:</strong> Sean Miller leads with $25,043 in total revenue. The top 20% of customers — identified using the NTILE window function — drive a disproportionate share of total sales, a classic pattern worth flagging to any sales or marketing team.</p>
<hr />
<h3>What does month-over-month growth look like?</h3>
<pre><code class="language-sql">WITH Monthly_Sales AS (
    SELECT 
        SUBSTR(`Order Date`, -4, 4) AS Year,
        PRINTF('%02d', CAST(SUBSTR(`Order Date`, 1, 
               INSTR(`Order Date`, '/') - 1) AS INTEGER)) AS Month,
        ROUND(SUM(Sales), 2) AS Total_Sales
    FROM orders
    GROUP BY Year, Month
),
Sales_With_Lag AS (
    SELECT 
        Year,
        Month,
        Total_Sales,
        LAG(Total_Sales) OVER (ORDER BY Year, Month) AS Prev_Month_Sales
    FROM Monthly_Sales
)
SELECT 
    Year,
    Month,
    Total_Sales,
    Prev_Month_Sales,
    ROUND((Total_Sales - Prev_Month_Sales) / Prev_Month_Sales * 100, 2) 
    AS MoM_Growth_Pct
FROM Sales_With_Lag
WHERE Prev_Month_Sales IS NOT NULL
ORDER BY Year, Month;
</code></pre>
<p><strong>Result:</strong> Sales consistently spike in September and November every year. The November spike in particular is dramatic — suggesting strong end-of-year purchasing behaviour that the business can plan around.</p>
<h2>Tableau: Visualising the Findings</h2>
<p>With the analysis complete, I built four visualisations in Tableau Public and combined them into a single interactive dashboard.</p>
<p>Viz 1 — Sales &amp; Profit by Region</p>
<p>📸 [INSERT SCREENSHOT: Sales &amp; Profit by Region bar chart here]</p>
<p>The West dominates on both metrics. What stands out is the Central region — third in sales but with a noticeably smaller profit bar relative to its sales volume, pointing to a margin problem rather than a volume problem.</p>
<p>Viz 2 — Top 10 Sub-Categories by Profit</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/df98ce40-a971-4651-ba0c-1b4cb28c73ee.png" alt="" style="display:block;margin:0 auto" />

<p>Copiers, Phones, and Accessories are the top three. The colour gradient from dark green to red immediately communicates relative performance — a deliberate design choice to make the chart readable at a glance.</p>
<p>Viz 3 — Monthly Sales Trend</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/2a618c85-37d0-4fe7-bbe2-1d2926657b2f.png" alt="" style="display:block;margin:0 auto" />

<p>This chart makes the seasonality unmistakable. Every single year, sales climb steeply in November before dropping back in January. A business sitting on this data should be pre-loading inventory and launching marketing campaigns in October to capture that spike.</p>
<p>Viz 4 — Discount vs Profit Scatter Plot</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/3eaab221-3f76-4a7e-be33-36696587abcb.png" alt="" style="display:block;margin:0 auto" />

<p>This is the most visually compelling chart in the project. Each dot represents a sub-category, coloured by product category. The downward-sloping trend lines across all three categories confirm what the SQL query proved — as average discount increases, average profit falls. The dots clustering near zero discount with the highest profit values tell the story clearly.</p>
<p>The Full Dashboard</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/13fde98c-a24d-459f-8733-2272ad1eef67.png" alt="" style="display:block;margin:0 auto" />

<p>🔗 View the interactive dashboard on Tableau Public : <a href="https://public.tableau.com/app/profile/tess.kamau/viz/SuperstoreSalesAnalysis%5C_17765991673530/SuperstoreSalesDashboard?publish=yes">https://public.tableau.com/app/profile/tess.kamau/viz/SuperstoreSalesAnalysis\_17765991673530/SuperstoreSalesDashboard?publish=yes</a></p>
<p>Key Findings Summary</p>
<ol>
<li><p>The West is the strongest region — highest sales and highest profit, suggesting the right product mix and pricing discipline.</p>
</li>
<li><p>Central region has a margin problem — not a volume problem. Sales are respectable but profit is being lost somewhere, likely through over-discounting.</p>
</li>
<li><p>Tables, Bookcases and Supplies are loss-makers — across four full years of data, these three sub-categories never turned a profit. That is not a bad month — that is a structural problem.</p>
</li>
<li><p>Discounts above 20% are destroying profit — this is the single most actionable finding. The data shows a clear breakpoint at 20%. Above that threshold, the business is essentially paying customers to take its products.</p>
</li>
<li><p>Technology is the star category — lowest average discount (13%), highest total profit ($146,543). The business should be leaning into this, not discounting it away.</p>
</li>
<li><p>Q4 is predictably strong every year — four years of consistent November spikes means this is not luck, it is a pattern. Plan for it.</p>
</li>
</ol>
<p>Recommendations Based on this analysis, here is what I would recommend to the business:</p>
<p>Cap all discounts at 20% and require approval for anything above that threshold Conduct a full review of the Furniture category — specifically Tables and Bookcases. Either reprice, renegotiate supplier costs, or discontinue Invest in Technology inventory ahead of Q4 — the seasonal pattern is consistent enough to plan around with confidence Build a top-customer retention programme — the top 20% of customers by revenue deserve personalised engagement, not generic marketing Track Central region margins quarterly — the gap between its sales rank and profit rank needs to be monitored and addressed</p>
<p>What I Learned This project taught me how much more powerful analysis becomes when you combine tools rather than rely on just one. Excel was perfect for exploration and quick summaries. SQL let me ask precise business questions and handle aggregations that would have been clunky in pivot tables. Tableau turned the numbers into something anyone in the business could understand in thirty seconds. The most important skill I practised was not a technical one — it was learning to ask so what? after every query result. Numbers without context are just numbers. The value is in the interpretation.</p>
<p>Project Files</p>
<p>🐙 GitHub Repository: github.com/Tee-ai63 📊 Live Tableau Dashboard: View here : <a href="https://public.tableau.com/app/profile/tess.kamau/viz/SuperstoreSalesAnalysis%5C_17765991673530/SuperstoreSalesDashboard?publish=yes">https://public.tableau.com/app/profile/tess.kamau/viz/SuperstoreSalesAnalysis\_17765991673530/SuperstoreSalesDashboard?publish=yes</a></p>
<p>Thanks for reading. If you found this useful or have feedback, connect with me on LinkedIn. I am actively building my data analyst portfolio and always open to conversations about data, analysis and career development.</p>
]]></content:encoded></item><item><title><![CDATA[Does Price Drive Customer Satisfaction? I Analyzed 171,000 Reviews to Find Out]]></title><description><![CDATA[The Short Answer: No. Here's What the Data Actually Says.]]></description><link>https://pric.hashnode.dev/does-price-drive-customer-satisfaction-i-analyzed-171-000-reviews-to-find-out</link><guid isPermaLink="true">https://pric.hashnode.dev/does-price-drive-customer-satisfaction-i-analyzed-171-000-reviews-to-find-out</guid><dc:creator><![CDATA[Tee Wanjiru]]></dc:creator><pubDate>Mon, 20 Apr 2026 21:44:08 GMT</pubDate><content:encoded><![CDATA[<h3>Problem Statement</h3>
<p>E-commerce businesses operate on an assumption so common it is rarely questioned: charge more, deliver more. The logic feels intuitive — premium pricing signals premium quality, and premium quality earns better reviews. But is that actually true?</p>
<p>This project set out to test that assumption rigorously. Using 171,000+ real customer reviews from Amazon and Flipkart, combined with 60 years of World Bank inflation data, I built an end-to-end data pipeline to answer one question: <strong>does product price predict customer satisfaction?</strong></p>
<p>The answer, backed by two machine learning models and 171,378 data points, is a clear no.</p>
<h2>Project Objectives</h2>
<ol>
<li><p>Build a production-structured data pipeline from raw CSV ingestion to a deployed interactive dashboard</p>
</li>
<li><p>Investigate the statistical relationship between product price and customer ratings</p>
</li>
<li><p>Compare a baseline ML model (Linear Regression) against a stronger model (Random Forest Classifier) to validate the finding</p>
</li>
<li><p>Use NLP word clouds to surface what actually drives satisfaction and dissatisfaction</p>
</li>
<li><p>Add macroeconomic context by analysing Kenya's inflation trends against global benchmarks</p>
</li>
<li><p>Deploy a live Streamlit dashboard that makes the findings interactive and accessible</p>
</li>
</ol>
<h3>Target Audience</h3>
<p>This project is relevant to three groups. E-commerce businesses and product managers who want to understand what actually moves the needle on customer satisfaction. Data analysts and hiring managers evaluating portfolio work — this project demonstrates a full pipeline from raw data to deployed product. And fellow analysts learning how to structure a Python data project beyond Jupyter notebooks.</p>
<h3>The Dataset</h3>
<p>Two datasets power this project.</p>
<p><strong>E-commerce Reviews (sentiment.csv)</strong> Source: Amazon/Flipkart Product Reviews via Kaggle 171,380 rows of customer reviews including product price, star rating (1–5), and review text. The price column required significant cleaning — values came with ₹ symbols, commas, and inconsistent formatting. Ratings were stored as floats and needed type conversion.</p>
<p><strong>World Bank Inflation Data (API_FP.CPI.TOTL.ZG)</strong> Source: World Bank Open Data CPI inflation rates for 217 countries spanning 1960–2024. This dataset arrived in wide format — one column per year — which required a reshape operation (melt) to convert into a usable time-series format. The Kenya comparison layer was added to ground the economic analysis in an emerging market context relevant to my broader portfolio work.</p>
<h2>How I Built It — The Full Pipeline</h2>
<h3>Step 1: Project Structure</h3>
<p>Before writing a single line of analysis, I structured the project as a proper pipeline rather than a single notebook. Every stage has its own script with a single responsibility:</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/624f560c-9076-415e-b54a-041f9b48e6a4.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Why this structure?</strong> Monolithic notebooks are fine for exploration but fragile in practice. If cleaning breaks, you don't want to re-run your ML code. Modular scripts mean each stage can be tested, debugged, and re-run independently.</p>
<hr />
<p><strong>Step 2: Data Ingestion — ingest_</strong><a href="http://data.py"><strong>data.py</strong></a></p>
<p>The first script migrates all raw CSV files into a structured SQLite database.</p>
<pre><code class="language-python"># 1. Define paths (Using relative paths is best practice)
DB_PATH = "data/ecommerce_analysis.db"
RAW_DATA_PATH = "data/raw/"


def ingest_data():
    # Connect to (or create) the SQLite database
    conn = sqlite3.connect(DB_PATH)
    print(f"--- Connected to {DB_PATH} ---")

    # A. Ingest Sentiment Data
    print("Loading sentiment data...")
    df_sentiment = pd.read_csv(
        os.path.join(RAW_DATA_PATH, "sentiment.csv"),
        encoding="ISO-8859-1",
        on_bad_lines="skip",
    )
    df_sentiment.to_sql("reviews", conn, if_exists="replace", index=False)
    print("Successfully loaded 'reviews' table.")

    # B. Ingest Inflation Data (Skip first 4 rows of metadata)
    print("Loading inflation data...")
    df_inflation = pd.read_csv(
        os.path.join(RAW_DATA_PATH, "API_FP.CPI.TOTL.ZG_DS2_en_csv_v2_287.csv"),
        skiprows=4,
    )
    df_inflation.to_sql("inflation_raw", conn, if_exists="replace", index=False)
    print("Successfully loaded 'inflation_raw' table.")

    # C. Ingest Country Metadata
    print("Loading country metadata...")
    df_metadata = pd.read_csv(
        os.path.join(
            RAW_DATA_PATH, "Metadata_Country_API_FP.CPI.TOTL.ZG_DS2_en_csv_v2_287.csv"
        )
    )
    df_metadata.to_sql("country_metadata", conn, if_exists="replace", index=False)
    print("Successfully loaded 'country_metadata' table.")

    conn.close()
    print("--- Ingestion Complete. Connection Closed. ---")


if __name__ == "__main__":
    ingest_data()
</code></pre>
<p><strong>Why SQLite?</strong> For a project of this size (171K rows), SQLite is the right tool. It is serverless, requires zero configuration, lives as a single file, and supports full SQL syntax. It also demonstrates that I understand relational database principles — which matters more to hiring managers than which specific database tool you use.</p>
<p>The inflation CSV required <code>skiprows=4</code> to skip World Bank metadata headers before the actual column names. A small detail that breaks pipelines if you miss it.</p>
<hr />
<h3>Step 3: Data Cleaning — clean_<a href="http://data.py">data.py</a></h3>
<p>Two non-trivial transformations happened here.</p>
<p><strong>Currency normalisation:</strong></p>
<pre><code class="language-python">df_reviews['ProductPrice'] = pd.to_numeric(
    df_reviews['ProductPrice'].astype(str).str.replace(r'[^\d.]', '', regex=True),
    errors='coerce'
)
</code></pre>
<p>The regex <code>[^\d.]</code> strips everything that is not a digit or decimal point — ₹ symbols, commas, spaces. <code>errors='coerce'</code> converts anything that still can't be parsed to NaN, which gets dropped downstream. This is the correct production approach: never assume your source data is clean.</p>
<p><strong>The inflation melt:</strong></p>
<pre><code class="language-python">df_melted = df_inflation.melt(
    id_vars=['Country Name', 'Country Code'],
    value_vars=year_columns,
    var_name='Year',
    value_name='InflationRate'
)
</code></pre>
<p>The World Bank ships inflation data in wide format — 60+ columns, one per year. This is human-readable but useless for time-series analysis. The <code>melt()</code> operation reshapes it into long format: one row per country per year. This is a fundamental data engineering operation that trips up many junior analysts.</p>
<pre><code class="language-python">
DB_PATH = "data/ecommerce_analysis.db"


def clean_data():
    conn = sqlite3.connect(DB_PATH)

    # --- 1. CLEAN REVIEWS ---
    print("Cleaning reviews...")
    df_reviews = pd.read_sql("SELECT * FROM reviews", conn)

    # Remove any non-numeric characters from Price (like ₹, $, or commas)
    df_reviews["ProductPrice"] = pd.to_numeric(
        df_reviews["ProductPrice"].astype(str).str.replace(r"[^\d.]", "", regex=True),
        errors="coerce",
    )

    # Ensure Rate is a float
    df_reviews["Rate"] = pd.to_numeric(df_reviews["Rate"], errors="coerce")

    df_reviews.to_sql("reviews_clean", conn, if_exists="replace", index=False)

    # --- 2. NORMALIZE INFLATION (The "Melt") ---
    print("Normalizing inflation data...")
    df_inflation = pd.read_sql("SELECT * FROM inflation_raw", conn)

    # Identify the year columns (1960 to 2024)
    year_columns = [col for col in df_inflation.columns if col.isdigit()]

    # "Melt" the data from wide format to long format
    df_melted = df_inflation.melt(
        id_vars=["Country Name", "Country Code"],
        value_vars=year_columns,
        var_name="Year",
        value_name="InflationRate",
    )

    # Convert Year to integer and drop rows with missing inflation data
    df_melted["Year"] = df_melted["Year"].astype(int)
    df_melted = df_melted.dropna(subset=["InflationRate"])

    df_melted.to_sql("inflation_clean", conn, if_exists="replace", index=False)

    conn.close()
    print("--- Cleaning Complete: 'reviews_clean' and 'inflation_clean' created ---")


if __name__ == "__main__":
    clean_data()
</code></pre>
<h3>Step 4: Exploratory Analysis — <code>analyze_</code><a href="http://data.py"><code>data.py</code></a></h3>
<p>With clean data in the database, the analysis script pulled summary statistics and generated the first visualisations.</p>
<ul>
<li><p>Average rating: <strong>3.65 / 5</strong></p>
</li>
<li><p>Median product price: <strong>₹1,199</strong></p>
</li>
<li><p>Total reviews analysed: <strong>171,380</strong></p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/6f238f29-b9e2-4397-8c3d-b5f474f8fa5c.png" alt="" style="display:block;margin:0 auto" />

<p>Even at this exploratory stage, the regression line's near-zero slope hinted at the main finding. A steeper line would suggest price matters. This line is almost flat.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/3a4cc0c9-dd48-41aa-8cf0-66dc181f0a46.png" alt="" style="display:block;margin:0 auto" />

<h3>Step 5: Machine Learning — <code>predict_</code><a href="http://rating.py"><code>rating.py</code></a></h3>
<p>This is the analytical core of the project. I tested two models against the same question: can price predict a customer's star rating?</p>
<p><strong>Why two models?</strong></p>
<p>Linear Regression establishes a statistical baseline and gives us R² directly — a clean measure of how much variance in ratings price explains. But Linear Regression assumes a continuous target. Ratings are ordinal (1, 2, 3, 4, 5) — a classification problem. So I added a Random Forest Classifier as the stronger, more appropriate model for comparison.</p>
<p><strong>Why a train/test split?</strong></p>
<pre><code class="language-python">X_train, X_test, y_train_c, y_test_c = train_test_split(
    X, y_continuous, test_size=0.2, random_state=42
)
</code></pre>
<p>Evaluating a model on the same data you trained it on is a fundamental error — it reports how well the model memorised the data, not how well it generalises. An 80/20 split means both models were evaluated on 34,276 reviews they had never seen during training.</p>
<p><strong>Model 1: Linear Regression Results</strong></p>
<ul>
<li><p>R² = <strong>0.0026</strong></p>
</li>
<li><p>MAE = <strong>1.3698</strong></p>
</li>
<li><p>Slope = <strong>0.000009</strong></p>
</li>
</ul>
<p>Price explains <strong>0.26%</strong> of the variation in customer ratings. The slope means that for every ₹10,000 increase in price, the predicted rating moves by 0.09 stars. Statistically, this is nothing.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/9aac1b2c-5db8-4df6-92f4-337fb4a8c624.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Model 2: Random Forest Classifier Results</strong></p>
<ul>
<li><p>MAE = <strong>0.9879</strong></p>
</li>
<li><p>Improvement over baseline: <strong>27.9%</strong></p>
</li>
</ul>
<p>The Random Forest is a stronger model — it builds 100 decision trees and aggregates their votes, capturing non-linear relationships that Linear Regression misses. Yet even with this more powerful approach, it still cannot meaningfully predict ratings from price alone.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/f635d176-6b93-4691-8122-ede3b558fdaf.png" alt="" style="display:block;margin:0 auto" />

<p>Look closely at the confusion matrix. The model correctly identifies 5-star reviews with high recall (0.96) because they dominate the dataset — 80,136 of them. But it essentially fails on 2-star and 4-star reviews, predicting almost everything as either 1-star or 5-star.</p>
<p>This reveals something important: <strong>the data itself is bimodal</strong>. Customers are polarised. They either love a product or hate it. Middle-ground ratings are rare.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/19e083f9-205f-426a-b745-cbce8b295c43.png" alt="" style="display:block;margin:0 auto" />

<p>The distribution confirms it visually — 80,136 five-star reviews and 32,987 one-star reviews, with everything else clustered in between. This is not a model failure. It is an honest reflection of how customers actually behave.</p>
<hr />
<h3>Step 6: NLP Sentiment Analysis — <code>sentiment_</code><a href="http://visuals.py"><code>visuals.py</code></a></h3>
<p>If price does not drive ratings, what does? The review text holds the answer.</p>
<p>Word clouds were generated separately for 5-star and 1-star reviews, filtering out stopwords and platform names (amazon, flipkart, product, item).</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/ac1aa8b3-80e0-410f-8257-4c5ce1bb7c0c.png" alt="" style="display:block;margin:0 auto" />

<p>5-star reviews: <em>Mind blowing, Highly recommended, Must buy, Worth every penny, Simply awesome.</em> Customers are talking about perceived value and emotional delight — not price.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/f1ff16ba-0897-4a25-9fd1-7439211640f6.png" alt="" style="display:block;margin:0 auto" />

<p>1-star reviews: <em>Waste, Absolute rubbish, Disappointed, Useless, Terrible, Worst experience.</em> The language is about broken expectations — products that did not do what was promised, arrived damaged, or were not what was advertised. Again, nothing about price.</p>
<p><strong>Why word clouds and not TF-IDF?</strong></p>
<p>Word clouds are the right tool for this stage — they are fast to generate, visually immediate, and clearly communicate the finding to a non-technical audience. TF-IDF vectorisation with a text-based classifier is the logical next step (and would likely produce a far stronger model than price alone), but that is a separate project phase.</p>
<hr />
<h3>Step 7: Economic Context — <code>kenya_</code><a href="http://comparison.py"><code>comparison.py</code></a></h3>
<p>The inflation dataset gives this project its macroeconomic layer. I compared Kenya, India, and the global average post-2000 to contextualise how economic volatility relates to consumer behaviour.</p>
<img src="https://cdn.hashnode.com/uploads/covers/68cd29a3686952aaad1f9ccd/d1d3bc26-b12e-4a9e-9460-c17e3f220256.png" alt="" style="display:block;margin:0 auto" />

<p>Kenya's inflation peaked sharply around 2008 and again post-2020, significantly outpacing both India and the World average during those periods. The 2024 annotation shows Kenya at 4.5% — currently converging toward global norms after years of elevated volatility.</p>
<p><strong>Why include this?</strong></p>
<p>E-commerce consumer behaviour does not happen in an economic vacuum. In markets experiencing high inflation, purchasing decisions become more risk-sensitive. A customer paying a higher price during a high-inflation period has higher expectations and lower tolerance for failure. This context reframes the price/satisfaction finding: it is not just that price does not matter — it is that other factors (reliability, accuracy, delivery speed) matter disproportionately more, especially in price-sensitive emerging markets.</p>
<hr />
<h3>Step 8: The Dashboard — <a href="http://app.py"><code>app.py</code></a></h3>
<p>All outputs were combined into a live Streamlit dashboard</p>
<p><strong>Why Streamlit?</strong></p>
<p>Streamlit converts a Python script into a web app with minimal boilerplate. For a data analyst building a portfolio, it is the fastest path from analysis to something a recruiter can click. The dashboard includes an interactive sentiment word cloud toggle (positive/negative), the regression visualisation, and an ML-powered rating predictor in the sidebar.</p>
<p><strong>Deployment note:</strong> Streamlit Cloud does not have access to a local SQLite database. The solution was to export the cleaned reviews table to <code>reviews_clean.csv</code>, commit it to the repo, and rewrite <code>get_data()</code> to read from CSV instead of SQLite. The pipeline scripts still use SQLite locally — only the dashboard reads from CSV.</p>
<h2>Key Findings Summary</h2>
<table>
<thead>
<tr>
<th>Finding</th>
<th>Detail</th>
</tr>
</thead>
<tbody><tr>
<td>Price explains</td>
<td>0.26% of rating variance (R² = 0.0026)</td>
</tr>
<tr>
<td>Linear Regression MAE</td>
<td>1.3698</td>
</tr>
<tr>
<td>Random Forest MAE</td>
<td>0.9879 (27.9% improvement)</td>
</tr>
<tr>
<td>Dominant sentiment</td>
<td>Bimodal — customers love or hate, rarely neutral</td>
</tr>
<tr>
<td>5-star language</td>
<td>Value, delight, recommendation</td>
</tr>
<tr>
<td>1-star language</td>
<td>Broken expectations, damaged goods, wrong items</td>
</tr>
<tr>
<td>Kenya inflation peak</td>
<td>~26% (2008), currently 4.5% (2024)</td>
</tr>
</tbody></table>
<hr />
<h2>What I Would Do Next</h2>
<p>The honest answer to "what predicts customer ratings" is: the words customers write in their reviews, not the price they paid. The next phase of this project would implement TF-IDF feature extraction on the review text, train a text-based classifier, and compare its performance against the price-only models. My hypothesis is that a text-based model would achieve substantially higher accuracy — and the word clouds already hint at which features would matter most.</p>
<hr />
<h2>Technical Stack</h2>
<p>Python 3.10 · Pandas · NumPy · Scikit-Learn · Matplotlib · Seaborn · WordCloud · SQLite3 · Streamlit · Black · Flake8 · Git</p>
<hr />
<h2>Links</h2>
<ul>
<li><p>🔗 <strong>Live Dashboard:</strong> [your Streamlit URL]</p>
</li>
<li><p>💻 <strong>GitHub Repository:</strong> <a href="https://github.com/Tee-ai63/Ecommerce-sentiment-analysis">https://github.com/Tee-ai63/Ecommerce-sentiment-analysis</a></p>
</li>
<li><p>📊 <strong>Related Project:</strong> <a href="https://github.com/Tee-ai63/Kenya-Economic-Analysis">The Real Cost of Being Kenyan — Economic Analysis 2018–2024</a></p>
</li>
</ul>
<hr />
<p><em>Thanks for reading. If you found this useful or have questions about the methodology, drop a comment below.</em></p>
]]></content:encoded></item></channel></rss>