<?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 ADEWALE ASHOGBON on Medium]]></title>
        <description><![CDATA[Stories by ADEWALE ASHOGBON on Medium]]></description>
        <link>https://medium.com/@emmanuelwale83?source=rss-4200b6711968------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PsMVKBC5L7Iw-kv2</url>
            <title>Stories by ADEWALE ASHOGBON on Medium</title>
            <link>https://medium.com/@emmanuelwale83?source=rss-4200b6711968------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:37:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emmanuelwale83/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[Linear Regression Training Project: Real Estate Price Prediction]]></title>
            <link>https://medium.com/@emmanuelwale83/linear-regression-training-project-real-estate-price-prediction-c109ab851709?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/c109ab851709</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 20:43:55 GMT</pubDate>
            <atom:updated>2025-10-25T20:43:55.912Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project, we work with a housing dataset containing information about property prices in the Delhi region. The goal is to help a real estate company understand the key factors that influence house prices and build a predictive model to estimate property values based on these factors.</p><p>The dataset includes the following features:</p><p>Area: Total area of the property (in square feet)</p><p>Bedrooms: Number of bedrooms in the property</p><p>Bathrooms: Number of bathrooms in the property</p><p>Stories: Number of floors the property has</p><p>Parking: Number of parking spaces available</p><p>Mainroad: Whether the property is connected to the main road (yes/no)</p><p>Guestroom: Whether the property has a guest room (yes/no)</p><p>Basement: Whether the property has a basement (yes/no)</p><p>Hotwaterheating: Availability of hot water heating (yes/no)</p><p>Airconditioning: Availability of air conditioning (yes/no)</p><p>Prefarea: Whether the property is located in a preferred area (yes/no)</p><p>Project Objective</p><p>The company aims to:</p><p><strong>Identify the variables that significantly affect house prices (e.g., area, bedrooms, bathrooms, parking).</strong></p><p><strong>Build a Multiple Linear Regression model to quantitatively relate house prices to these features.</strong></p><p><strong>Evaluate the accuracy and performance of the model to understand how well these features predict property prices. Business Context</strong></p><p><strong>The insights from this analysis will enable the real estate company to make data-driven decisions on property valuation, pricing strategy, and investment prioritization—optimizing profits while offering fair market prices to clients.</strong></p><h3>Importing necessary libraries</h3><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import numpy as np</pre><p><strong>Getting the Data</strong></p><p>Note: As mentioned before, the data comes from a test dataset freely available on<a href="https://www.kaggle.com/code/ashydv/housing-price-prediction-linear-regression"> Kaggle</a> . Note that this is a training set, and the information does not correspond to real people.</p><h3>Exploratory Data Analysis (EDA)</h3><p>Before building the linear regression model, it is essential to explore and understand the dataset. The main objectives of this EDA phase are to:</p><ul><li>Understand the structure and quality of the dataset</li><li>Identify missing values, outliers, and data inconsistencies</li><li>Explore the distribution of variables and their relationships with the target variable (<em>price</em>)</li></ul><p>Detect potential multicollinearity between independent variables</p><h3>Initial Data Checks</h3><p><em>To understand the structure and quality of the dataset, we begin with the following checks:</em></p><pre>df = pd.read_csv(&#39;Housing.csv&#39;)<br>df.head()<br>df.shape               # Number of rows and columns<br>df.info()              # Column names, data types, non-null counts, memory usage<br>df.isnull().sum()      # Missing values per column<br>df.describe()          # Summary statistics for numerical columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5_7b-EJrVpZARB8e6shUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWVfnjmGbbl8MKnEfLbnrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75ZPORCgQLZXcm3_xQWv9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwsItpv2uRsL7XRCajkNHw.png" /></figure><p><strong>Findings:</strong></p><ul><li>The dataset contains <strong>545 rows and 13 columns</strong>.</li><li><strong>No missing values</strong> were found.</li><li>The columns have <strong>appropriate data types</strong> for analysis.</li></ul><p><strong>Descriptive Statistics Overview</strong></p><p><strong>Price</strong><br> Property prices range from <strong>1.75 million to 13.3 million</strong>, with an average (mean) of about <strong>4.77 million</strong>.<br> The <strong>median price (4.34 million)</strong> is slightly lower than the mean, indicating a <strong>right-skewed distribution</strong>—a few high-priced properties pull the average upward.<br> This wide price range suggests <strong>significant variation in housing values</strong>, likely influenced by factors such as <strong>location, property size, and available amenities</strong>.</p><p><strong>Area (sq. ft.)</strong><br> Property areas range from <strong>1,650 to 16,200 sq. ft.</strong>, with an average of around <strong>5,150 sq. ft.</strong><br> The <strong>high standard deviation</strong> shows that the dataset includes both <strong>compact apartments and large houses or villas</strong>, reflecting the <strong>diverse real estate market in Delhi</strong>.</p><p><strong>Bedrooms</strong><br> Properties have between <strong>1 and 6 bedrooms</strong>, with a <strong>median of 3 bedrooms</strong>, making it the most common configuration.<br> The relatively small variation indicates that <strong>most homes fall within a similar size category</strong> in terms of bedrooms.</p><p><strong>Bathrooms</strong><br> The number of bathrooms ranges from <strong>1 to 4</strong>, with an average of about <strong>1.3</strong>.<br> This suggests that <strong>most properties have 1 or 2 bathrooms</strong>, typical of <strong>mid-sized residential homes</strong>.</p><p><strong>Stories (Floors)</strong><br> Properties range from <strong>1 to 4 stories</strong>, with an average of approximately <strong>1.8</strong>, showing that <strong>single- and double-story homes are the most common</strong>.</p><p><strong>Parking</strong><br> Parking availability ranges from <strong>0 to 3</strong>, with an average of <strong>0.69</strong>.<br> This indicates that <strong>many properties have limited or no dedicated parking spaces</strong>, possibly reflecting <strong>urban density or property type differences</strong>.</p><h3>Data Visualization and Feature Relationships</h3><p>Next, we proceed to visualize the data using <strong>Sweetviz</strong> to gain deeper insights into feature distributions and their relationships with the target variable.</p><pre>!pip install sweetviz<br>pip install numpy==1.26.4<br>import sweetviz as sv<br>report= sv.analyze(df)<br>report.show_html(&quot;report.html&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vumhYkKqvHDwJh0z-_Qr5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcW5uwroorHDtShsnlTc5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2R1DLepSCsgJ_lPEStK93w.png" /><figcaption>images from Sweetviz</figcaption></figure><h3>Sweetviz Insights</h3><p>After analyzing the visualizations generated by Sweetviz, it was observed that both the <strong>target variable(price) </strong>and the <strong>area</strong> feature are <strong>highly skewed</strong>.<br> This suggests that the data are not normally distributed, and this can violate the linearity assumption of linear regression.</p><p>To confirm this, we visualized their distributions using histograms:</p><pre>sns.histplot(df[&#39;price&#39;], kde=True)<br>sns.histplot(df[&#39;area&#39;], kde=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*kbGRuXQiuUeOJFF0Ck1c2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*wu-4DuwG0Gay38a8uUZQsA.png" /><figcaption>Both plots clearly show <strong>right-skewed distributions</strong>, meaning a few properties have much higher prices and larger areas compared to the rest.</figcaption></figure><h3>Log Transformation</h3><p>Since <strong>linear regression assumes linear relationships</strong>, it is often useful to <strong>transform skewed variables</strong> using the natural logarithm to achieve linearity and stabilize variance.</p><pre>df[&#39;log_area&#39;] = np.log(df[&#39;area&#39;])<br>df[&#39;log_price&#39;] = np.log(df[&#39;price&#39;])</pre><p>After applying the log transformation, we visualized the relationships again to check if linearity improved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*PwXmV7bXG7EpEGP5Nn_GNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*afntFb404iw2CnLH_8IfRg.png" /></figure><pre>sns.pairplot(df,<br>             kind=&#39;scatter&#39;,<br>             plot_kws={&#39;alpha&#39;:0.4},<br>             diag_kws={&#39;alpha&#39;:0.55, &#39;bins&#39;:40}</pre><p><strong>Insights from sns.pairplot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nv51mkxOZ2-ylJ4Ghen4hQ.png" /><figcaption><strong>Figure: Pairplot showing linear relationship between </strong><strong>log_area and </strong><strong>log_price after transformation.</strong></figcaption></figure><p><strong>Interpretation:</strong></p><ul><li>The log transformation effectively reduced skewness and helped reveal a more linear pattern between property size and price.</li><li>This transformation step is crucial for improving the performance and interpretability of the upcoming regression model.</li></ul><h3>Correlation Analysis</h3><p>To further quantify the relationships between numeric variables, a correlation heatmap was generated:</p><pre># Compute correlation for numeric columns only<br>corr = df.select_dtypes(include=[&#39;number&#39;]).corr()<br><br># Plot the heatmap<br>plt.figure(figsize=(10,6))<br>sns.heatmap(corr, annot=True, cmap=&#39;coolwarm&#39;, fmt=&quot;.2f&quot;)<br>plt.title(&#39;Correlation Heatmap&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xBRUlIn0X8a3V4aJvEerXQ.png" /><figcaption><strong>From the heatmap, we observe </strong><strong>log_area and </strong><strong>log_price show a strong positive correlation, confirming the results seen in the pairplot.</strong></figcaption></figure><h3>Linearity Check</h3><p>Finally, to visually confirm the linear relationship between log_area and log_price, a regression plot was drawn:</p><pre>sns.regplot(x=&quot;log_area&quot;, y=&quot;log_price&quot;, data=df, ci=None)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*R7sy-LoM-mtzTnqjuh4Ynw.png" /></figure><p><strong>The regression line fits closely to the data points, reinforcing that the log transformation successfully linearized the relationship—making the data well-prepared for linear regression modeling.</strong></p><h3>Model Building: Linear Regression</h3><p>After completing the exploratory data analysis and addressing skewness in the price and area variables through log transformation, we can now proceed to <strong>build a linear regression model</strong>.</p><p>The goal of this model is to understand how different property features—such as area, number of bedrooms, bathrooms, stories, and parking availability—influence house prices in the Delhi region.</p><h3>Feature Selection and Splitting the data</h3><p>We’ll use the transformed variables (log_price and log_area) along with other numeric predictors for modeling.</p><pre>from sklearn.model_selection import train_test_split<br><br># Define the numerical predictors<br>X = df[[&#39;log_area&#39;, &#39;bedrooms&#39;, &#39;bathrooms&#39;, &#39;stories&#39;, &#39;parking&#39;]]<br>y = df[&#39;log_price&#39;]<br>X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=42)</pre><h3>Model Training</h3><p>We use <strong>Linear Regression</strong> from sklearn.linear_model to fit our model.</p><pre>#training the model<br>from sklearn.linear_model import LinearRegression<br>lm=LinearRegression()<br>lm.fit(X_train,y_train)<br>print(&quot;Model fitted successfully!&quot;)</pre><h3>Model Evaluation</h3><pre>from sklearn.metrics import r2_score, mean_squared_error<br>import numpy as np<br><br>y_pred = lm.predict(X_test)<br><br>r2 = r2_score(y_test, y_pred)<br>rmse = np.sqrt(mean_squared_error(y_test, y_pred))<br><br>print(&quot;R-squared:&quot;, r2)<br>print(&quot;RMSE:&quot;, rmse)</pre><p>Our initial linear regression model, built with the log-transformed numerical variables (log_price and log_area), achieved the following performance metrics:</p><pre>R²: 0.5256<br>MAE: 0.2246<br>RMSE: 0.2869</pre><p>This indicates that the model explains about <strong>52.6% of the variance</strong> in property prices—a decent start, but there’s still room for improvement.</p><h3>Improving the R² and RMSE</h3><p>To enhance the model’s predictive power, we can incorporate <strong>categorical variables</strong> that may significantly influence property prices. Features such as whether a house is on the main road, has a guest room, or includes air conditioning often impact value beyond just physical characteristics like area or stories.</p><h3>Handling the Categorical Variables</h3><p>In this dataset, the following variables are categorical:</p><ul><li><strong>mainroad</strong> — whether the property is on the main road</li><li><strong>guestroom</strong> — presence of a guest room</li><li><strong>basement</strong> — whether the property includes a basement</li><li><strong>hotwaterheating</strong> — presence of hot water heating</li><li><strong>airconditioning</strong> — whether air conditioning is available</li><li><strong>prefarea</strong> — whether the property is in a preferred area</li><li><strong>furnishingstatus</strong> — level of furnishing (e.g., furnished, semi-furnished, unfurnished)</li></ul><h3>Encoding Strategy</h3><p>To use these categorical variables in the regression model, they must be <strong>numerically encoded</strong>.</p><h4>1. Label Encoding (for Binary Categories)</h4><p>For binary categorical variables (mainroad, guestroom, basement, hotwaterheating, airconditioning, prefarea), we can map “yes” and “no” responses to <strong>1 and 0</strong>, respectively, using manual binary encoding.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score, mean_squared_error<br># always start clean<br>df = pd.read_csv(&quot;Housing.csv&quot;)<br><br># log transforms<br>df[&#39;log_area&#39;] = np.log(df[&#39;area&#39;])<br>df[&#39;log_price&#39;] = np.log(df[&#39;price&#39;])<br><br># binary mappings<br>binary_cols = [&#39;mainroad&#39;, &#39;guestroom&#39;, &#39;basement&#39;, &#39;hotwaterheating&#39;,<br>               &#39;airconditioning&#39;, &#39;prefarea&#39;]<br>for col in binary_cols:<br>    df[col] = df[col].map({&#39;yes&#39;: 1, &#39;no&#39;: 0})</pre><h4>2. One-Hot Encoding (for Multi-Class Variables)</h4><p>The furnishingstatus column likely has three categories: &quot;furnished&quot;, &quot;semi-furnished&quot;, and &quot;unfurnished&quot;.<br> We use <strong>one-hot encoding</strong> to create dummy variables, dropping one to avoid multicollinearity.</p><pre># --- One-Hot Encoding ---<br># Perform one-hot encoding on the &#39;furnishingstatus&#39; column<br># drop_first=True removes one dummy column to avoid multicollinearity<br>df = pd.get_dummies(df, columns=[&#39;furnishingstatus&#39;], drop_first=True)</pre><p>Now the dataset is fully numeric and ready for model training.</p><h3>Rebuilding the Model</h3><p>Next, we include both numeric and encoded categorical features:</p><pre><br># Define the numerical predictors<br># build feature matrix and target<br>furnish_cols = [c for c in df.columns if c.startswith(&#39;furnishingstatus_&#39;)]<br>X = df[[&#39;log_area&#39;, &#39;bedrooms&#39;, &#39;bathrooms&#39;, &#39;stories&#39;, &#39;parking&#39;]<br>        + binary_cols + furnish_cols]<br>y = df[&#39;log_price&#39;]</pre><p>Then we re-split the data and retrain the model:</p><pre># train/test split<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.3, random_state=42<br>)<br><br># train model<br>lm = LinearRegression().fit(X_train, y_train)<br># evaluate<br>y_train_pred = lm.predict(X_train)<br>y_test_pred = lm.predict(X_test)<br><br>print(f&quot;Training R²: {r2_score(y_train, y_train_pred):.4f}&quot;)<br>print(f&quot;Testing  R²: {r2_score(y_test, y_test_pred):.4f}&quot;)<br>print(f&quot;RMSE: {np.sqrt(mean_squared_error(y_test, y_test_pred)):.4f}&quot;)</pre><h3>Model Performance After Adding Categorical Variables</h3><p>After encoding and adding the categorical features to the regression model, the performance metrics improved significantly:</p><pre>Training R²: 0.7233<br>Testing  R²: 0.6674<br>RMSE: 0.2402</pre><h3>Interpretation of Results</h3><ul><li>The <strong>Training R² of 0.7233</strong> means that the model explains about <strong>72% of the variation</strong> in property prices in the training data.</li><li>The <strong>Testing R² of 0.6674</strong> indicates that the model generalizes well to unseen data, explaining about <strong>67% of price variation</strong> on the test set.</li><li>The <strong>RMSE of 0.2402</strong> shows that the model’s prediction errors are relatively low, suggesting good overall accuracy.</li><li>Compared to the previous model (R² = 0.5256, RMSE = 0.2869), this version is <strong>significantly better</strong> in both fit and predictive performance.</li></ul><h3>Why the Model Improved</h3><p>The improvement can be attributed to the inclusion of <strong>categorical variables</strong> that capture additional, non-numeric aspects of property value—such as</p><ul><li>Whether the property is on the <strong>main road</strong> (influences accessibility and desirability)</li><li>The presence of <strong>amenities</strong> like a <strong>guest room</strong>, <strong>basement</strong>, <strong>air conditioning</strong>, and <strong>hot water heating</strong></li><li>Being located in a <strong>preferred area</strong></li><li>The <strong>furnishing status</strong>, which directly affects market value</li></ul><p>These features complement the numerical predictors (like area, bedrooms, bathrooms, and stories), helping the model better explain real-world price variations.</p><h3>Model Summary</h3><p>By incorporating categorical variables:</p><ul><li>The <strong>model became more representative</strong> of real-world housing conditions.</li><li>The <strong>R² improved from 0.52 to 0.67</strong>, indicating stronger explanatory power.</li><li>The <strong>RMSE dropped from 0.29 to 0.24</strong>, meaning more accurate predictions.</li></ul><p>Overall, the improved model provides a <strong>more reliable foundation</strong> for understanding the factors influencing property prices in the Delhi region.</p><h3>Model Interpretation and Insights</h3><p>To understand how each feature contributes to house prices, we examine the model’s coefficients:</p><pre>lm.coef_<br>cdf=pd.DataFrame(lm.coef_,X.columns,columns=[&#39;Coed&#39;])<br>print(cdf)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YH83CEcNiKBmfOSpczJ8hg.png" /></figure><h3>Key Interpretations</h3><p>Since we used a <strong>log-log model</strong> (both price and area were log-transformed), the coefficients can be interpreted in <strong>percentage terms</strong> — each coefficient represents the <em>expected percentage change in price</em> for a 1% change in that feature, holding others constant.</p><h4>🔹 log_area (0.3162)</h4><ul><li>The most influential variable in the model.</li><li>A <strong>1% increase in property area</strong> is associated with approximately a <strong>0.32% increase in price</strong>, assuming other features stay the same.</li><li>So, for example :<br> if a house is worth <strong>₦10,000,000</strong>, and its area increases by <strong>1%</strong>,<br> the price would rise by roughly <strong>₦32,000</strong> (which is 0.32% of ₦10,000,000).</li><li>Larger houses, as expected, command higher prices.</li></ul><h4>🔹 bathrooms (0.1833)</h4><ul><li>Each additional bathroom increases the log of price by about <strong>0.18</strong>, reflecting that homes with more bathrooms are more comfortable and therefore more valuable.</li></ul><h4>🔹 airconditioning (0.1254) and basement (0.1201)</h4><ul><li>Both features strongly increase the property’s price.</li><li>Homes with air conditioning or a basement are typically more luxurious and have higher market demand.</li></ul><h4>🔹 hotwaterheating (0.1150) and prefarea (0.1071)</h4><ul><li>Properties with hot water heating or located in preferred areas have noticeably higher prices, indicating the premium value buyers place on convenience and location.</li></ul><h4>🔹 mainroad (0.0855) and stories (0.0830)</h4><ul><li>Being located on the main road and having more stories slightly boost property prices — better accessibility and vertical space utilization add value.</li></ul><h4>🔹 parking (0.0447) and guestroom (0.0432)</h4><ul><li>Both contribute positively but moderately to price.</li><li>Having dedicated parking or an extra guest room adds functional benefits that buyers appreciate.</li></ul><h4>🔹 furnishingstatus</h4><ul><li><strong>Semi-furnished:</strong> negligible effect (−0.0016), meaning its price difference from fully furnished homes is minimal.</li><li><strong>Unfurnished:</strong> negative impact (−0.1115), showing that <strong>unfurnished properties are valued lower</strong> compared to furnished ones, all else being equal.</li></ul><h4>🔹 bedrooms (0.0223)</h4><ul><li>Has a small positive impact after accounting for area — meaning once size is considered, simply adding more bedrooms doesn’t change price drastically.</li></ul><h3>Overall Insights</h3><ul><li><strong>Area</strong> remains the dominant factor driving house prices.</li><li><strong>Luxury and comfort features</strong> — like air conditioning, basements, and hot water heating — substantially raise property value.</li><li><strong>Location and accessibility</strong> (main road, preferred area) also play key roles.</li><li><strong>Furnishing level</strong> matters: furnished homes are valued higher, while unfurnished ones lose some value.</li><li>Together, these variables explain about <strong>67% of the variation</strong> in property prices, making the model both interpretable and practically useful.</li></ul><h3>Final Note</h3><p>This model offers valuable insights for both <strong>real estate investors and developers</strong> in the Delhi region.<br> It highlights how physical space, amenities, and location-based features combine to influence pricing — helping guide smarter decisions on property valuation and investment strategy.</p><h3>Residual Analysis</h3><p>To assess how well the model fits the data, a residual plot was generated by plotting predicted values against residuals (actual − predicted).</p><p>If the residuals are randomly distributed around zero, it indicates that the model’s predictions are unbiased and the linear regression assumptions hold true.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Residuals<br>residuals = y_test - y_pred<br><br>plt.figure(figsize=(8,5))<br>sns.scatterplot(x=y_pred, y=residuals)<br>plt.axhline(y=0, color=&#39;r&#39;, linestyle=&#39;--&#39;)<br>plt.xlabel(&#39;Predicted Values&#39;)<br>plt.ylabel(&#39;Residuals&#39;)<br>plt.title(&#39;Residual Plot&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*jbOlHy_T-poVXF9cr4jjsQ.png" /><figcaption><strong>The residual plot above shows the relationship between the predicted house prices and the residuals (the differences between actual and predicted values).</strong></figcaption></figure><p><strong>Interpretation (example)</strong>:<br> The residuals appear randomly scattered around zero, suggesting that the model captures the relationship between the predictors and house prices well, with no major signs of heteroscedasticity or non-linearity.</p><p>A few points lie farther from the zero line, but these likely represent natural variation or possible outliers rather than systematic bias.</p><p><strong>Conclusion:</strong><br> The residual analysis supports that the linear regression model is appropriate for this dataset and that the errors are randomly distributed, validating the model’s reliability.</p><h3>📊 Model Summary</h3><p>After incorporating both numerical and categorical features into the linear regression model, the model achieved a <strong>training R² of 0.7233</strong> and a <strong>testing R² of 0.6674</strong>, indicating that it explains approximately <strong>66.7% of the variance</strong> in house prices on unseen data.<br> The <strong>RMSE of 0.2402</strong> shows that the model’s predictions are relatively close to the actual log-transformed prices, suggesting good predictive accuracy.</p><p>Furthermore, the <strong>residual plot</strong> shows a random scatter around the zero line, confirming that the <strong>linearity and homoscedasticity assumptions</strong> of linear regression are reasonably satisfied. There is no visible pattern in the residuals, indicating that the model does not suffer from systematic bias.</p><p>Overall, the model demonstrates a strong relationship between property features and price, with <strong>log(area)</strong> emerging as the most influential predictor, followed by <strong>bathrooms</strong>, <strong>air conditioning</strong>, and <strong>basement presence</strong>.</p><h3>🧾 Equation of the Best-Fit Line</h3><p>Based on the trained model’s coefficients, we can express the <strong>equation of our best-fitted line</strong> (in log-transformed space) as:</p><p>log(price)=0.32(log(area))+0.18(bathrooms)+0.08(stories)+0.12(basement)+0.13(airconditioning)+0.11(prefarea)+0.04(parking)+other minor terms.</p><p>In simpler terms (without the log transformation), this means that:</p><blockquote><strong><em>Price increases significantly with area, number of bathrooms, stories, and amenities like air conditioning, basement, and preferred area location.</em></strong></blockquote><p>We can summarize this relationship as:</p><p>price≈0.35×area+0.20×bathrooms+0.19×stories+0.10×airconditioning+0.10×parking+0.11×prefarea</p><p>This simplified version highlights the main drivers of property prices in the dataset.</p><h3>🚀 Conclusion and Next Steps</h3><p>The multiple linear regression model, after applying log transformation and encoding categorical features, achieved <strong>a good predictive performance (Testing R² ≈ 0.67, RMSE ≈ 0.24)</strong>.<br> The model effectively captures the relationship between key features and property prices in the Delhi housing dataset.</p><p>However, there is still room for improvement. Future steps could include:</p><ul><li><strong>Feature engineering</strong> (e.g., creating interaction terms between area and location).</li><li><strong>Outlier treatment</strong> or <strong>removing high-leverage points</strong> to further stabilize predictions.</li><li>Trying <strong>non-linear models</strong> like <strong>Random Forest</strong>, <strong>XGBoost</strong>, or <strong>Gradient Boosting Regressor</strong>, which can capture more complex relationships between features and price.</li><li>Using <strong>cross-validation</strong> to better generalize performance.</li></ul><p>Overall, this analysis provides a strong baseline for understanding the key factors influencing house prices and sets a solid foundation for more advanced predictive modeling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c109ab851709" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Analysis of the Parch and Posey Dataset using SQL and Power BI]]></title>
            <link>https://medium.com/@emmanuelwale83/an-analysis-of-the-parch-and-posey-dataset-using-sql-and-power-bi-f27be4254bd9?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/f27be4254bd9</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 20:47:02 GMT</pubDate>
            <atom:updated>2024-09-26T20:47:02.330Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>PROJECT DESCRIPTION</strong></h3><p><strong>STATEMENT OF PURPOSE</strong></p><p>The goal of this project is to give you practical experience obtainable in a business environment as a data analyst. The main idea is to encourage individual analytical thinking for insight generation.</p><p><strong>DESCRIPTION</strong></p><p><strong>Disclaimer: The dataset used and its application case are fictional, however, they mirror real life scenarios and problems which can be faced by real life data analysts in real life companies.</strong></p><p>Parch and Posey is a company that deals with the sale of three distinct paper types to its clients. The Parch and Posey dataset contains 5 tables with varying number of columns, all linked via primary keys and foreign keys. Each table contains important information on customers, their orders and its characteristics, their purchase regions, assigned sales representatives, and the route from which they were integrated into the company.</p><p>The tables include <strong>accounts</strong>, <strong>orders</strong>, <strong>region</strong>, <strong>sales_reps </strong>and <strong>web_events.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*kKOyXIcWybd3ZCOduTefKw.png" /></figure><p>As a newly employed data analyst, you are expected to access the company’s database (using SQL), analyse the dataset and generate <strong>10 </strong>insights which will aid data-driven decision making. Important insights should be visualized using a business intelligence tool for presentation to stakeholders.</p><h3>Case Study Questions</h3><p>I used ChatGpt to generate these following 10 questions :</p><p>—1. Top 5 Sales Reps by Total Revenue Generated</p><p>— 2. What is the total number of orders by region?</p><p>— 3. Which product type (standard, poster, or gloss) generates the most orders?</p><p>— 4. What is the average order value for each product type?</p><p>— 5. What is the conversion rate from web events to actual orders?</p><p>— 6. Which region generates the highest revenue?</p><p>— 7. What is the customer retention rate over the past year?</p><p>— 8. What is the distribution of web events by region?</p><p>— 9. Which customers placed the most orders?</p><p>— 10. What is the total revenue from new customers vs. returning customers?</p><h4><strong>SOLUTION</strong></h4><p>For the Case study, I used PostgreSQL</p><p>— 1. Top 5 Sales Reps by Total Revenue Generated</p><pre>-- This query calculates the total revenue (from the orders table) per sales rep.<br>SELECT sr.name AS sales_rep_name, SUM(o.total_amt_usd) AS total_revenue<br>FROM sales_reps sr<br>JOIN accounts a ON sr.id = a.sales_rep_id<br>JOIN orders o ON a.id = o.account_id<br>GROUP BY sr.name<br>ORDER BY total_revenue DESC<br>LIMIT 5;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*bQrSdY3Db2yALHDo-hH-jw.png" /></figure><p>Answer :</p><p>Earlie Schleusner : 1098137.72<br>Tia Amato : 1010690.60<br>Vernita Plump : 934212.93<br>Georgianna Chisholm : 886244.12<br>Arica Stoltzfus : 810353.34</p><p>— 2. What is the total number of orders by region?</p><pre>--This query calculates the total number of orders placed by customers in each region.<br>SELECT r.name AS region_name, COUNT(o.id) AS total_orders<br>FROM region r<br>JOIN sales_reps sr ON r.id = sr.region_id<br>JOIN accounts a ON sr.id = a.sales_rep_id<br>JOIN orders o ON a.id = o.account_id<br>GROUP BY r.name<br>ORDER BY total_orders DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*-NYNMdbTs3itlzAKdPXRYA.png" /></figure><p>Answer :</p><p>Northeast 2357 orders</p><p>Southeast 2024 orders</p><p>West 1634 orders</p><p>Midwest 897 orders</p><p><strong>To calculate the total number of orders across all regions, you simply sum these values:</strong></p><p><strong>Total Orders=2357+2024+1634+897=6912</strong></p><p>— 3. Which product type (standard, poster, or gloss) generates the most orders?</p><pre> --This query calculates the total quantity ordered for each paper type (standard, poster, gloss).<br> SELECT  <br>   &#39;Standard&#39; AS product_type, SUM(o.standard_qty) AS total_quantity<br> FROM orders o<br> UNION<br> SELECT <br>   &#39;Poster&#39; AS product_type, SUM(o.poster_qty) AS total_quantity<br> FROM orders o<br> UNION<br> SELECT <br>   &#39;Gloss&#39; AS product_type, ROUND(SUM(<br>     CASE <br>       WHEN o.total_amt_usd &gt; 0 THEN o.gloss_amt_usd / o.total_amt_usd * o.total <br>       ELSE 0 <br>     END<br>   ) ,0)AS total_quantity<br> FROM orders o<br> ORDER BY total_quantity DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*7SFmowdF2NJiNFaZf6nLzQ.png" /></figure><p>Answer:</p><p>Standard 1938346<br>Gloss 1077794<br>Poster 723646</p><p>— 4. What is the average order value for each product type?</p><pre>--This query calculates the average value for each type of product ordered.<br><br>SELECT <br>  &#39;Standard&#39; AS product_type, ROUND(AVG(o.standard_amt_usd),1) AS avg_order_value<br>FROM orders o<br>UNION<br>SELECT <br>  &#39;Poster&#39; AS product_type, ROUND(AVG(o.poster_amt_usd),1) AS avg_order_value<br>FROM orders o<br>UNION<br>SELECT <br>  &#39;Gloss&#39; AS product_type, ROUND(AVG(o.gloss_amt_usd),1) AS avg_order_value<br>FROM orders o<br>ORDER BY avg_order_value DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*Wui_0B7QPacWfMn5TYCvRQ.png" /></figure><p>Answer :</p><p>Standard 1399.4<br>Gloss 1098.5<br>Poster 850.1</p><p>— 5. What is the conversion rate from web events to actual orders?</p><pre>--This query calculates the conversion rate of web events into actual orders, per account<br><br>WITH web_engagement AS (<br>  SELECT we.account_id, COUNT(we.id) AS web_events<br>  FROM web_events we<br>  GROUP BY we.account_id<br>),<br>orders_data AS (<br>  SELECT o.account_id, COUNT(o.id) AS total_orders<br>  FROM orders o<br>  GROUP BY o.account_id<br>)<br>SELECT we.account_id, <br>  (total_orders::float / web_events) AS conversion_rate<br>FROM web_engagement we<br>JOIN orders_data o ON we.account_id = o.account_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*cnxJHHmtHhY4aah0GMltGg.png" /></figure><p>— 6. Which region generates the highest revenue?</p><pre>--This query calculates the total revenue for each region.<br>SELECT r.name AS region_name, SUM(o.total_amt_usd) AS total_revenue<br>FROM region r<br>JOIN sales_reps sr ON r.id = sr.region_id<br>JOIN accounts a ON sr.id = a.sales_rep_id<br>JOIN orders o ON a.id = o.account_id<br>GROUP BY r.name<br>ORDER BY total_revenue DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*oLy-JpcEnlLGyqirZVT9Xw.png" /></figure><p>Northeast 7744405.36<br>Southeast 6458497.00<br>West 5925122.96<br>Midwest 3013486.51</p><p>— 7. What is the customer retention rate over the past year?</p><pre>--This query calculates the retention rate of customers who placed more than one order.<br><br>WITH first_orders AS (<br>  SELECT account_id, MIN(occurred_at) AS first_order_date<br>  FROM orders<br>  GROUP BY account_id<br>),<br>repeat_customers AS (<br>  SELECT o.account_id, COUNT(o.id) AS order_count<br>  FROM orders o<br>  JOIN first_orders fo ON o.account_id = fo.account_id<br>  WHERE o.occurred_at &gt; fo.first_order_date<br>  GROUP BY o.account_id<br>)<br>SELECT (COUNT(account_id)::float / (SELECT COUNT(account_id) FROM first_orders)) AS retention_rate<br>FROM repeat_customers;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*t5xePinqMzvqIiZxvLwXqw.png" /></figure><p>— 8. What is the distribution of web events by region?</p><pre>- This query calculates the total number of web events per region.<br>SELECT r.name AS region_name, COUNT(we.id) AS total_web_events<br>FROM region r<br>JOIN sales_reps sr ON r.id = sr.region_id<br>JOIN accounts a ON sr.id = a.sales_rep_id<br>JOIN web_events we ON a.id = we.account_id<br>GROUP BY r.name<br>ORDER BY total_web_events DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*WvA40VDWhH4XeKiBeWqd5g.png" /></figure><p>— 9. Which customers placed the most orders?</p><pre>--This query identifies the top 5 customers who placed the highest number of orders.<br>SELECT a.name AS account_name, COUNT(o.id) AS total_orders<br>FROM accounts a<br>JOIN orders o ON a.id = o.account_id<br>GROUP BY a.name  <br>ORDER BY total_orders DESC<br>LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*i_68ZGq0vtN_eCE2HbJuQA.png" /></figure><p>— 10. What is the total revenue from new customers vs. returning customers?</p><pre>--This query compares the total revenue generated by new and returning customers.<br><br>WITH first_time_orders AS (<br>  SELECT account_id, MIN(occurred_at) AS first_order<br>  FROM orders<br>  GROUP BY account_id<br>)<br>SELECT<br>  CASE<br>    WHEN o.occurred_at = fto.first_order THEN &#39;New Customer&#39;<br>    ELSE &#39;Returning Customer&#39;<br>  END AS customer_type,<br>  SUM(o.total_amt_usd) AS total_revenue<br>FROM orders o<br>JOIN first_time_orders fto ON o.account_id = fto.account_id<br>GROUP BY customer_type;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*RlhNImCnrPadR2t6qHXEog.png" /></figure><h3>#INSIGHT</h3><h3>From the analysis, we discover the following</h3><ul><li><strong>Top 5 Sales Reps by Total Revenue Generated</strong>:</li><li><strong>Insight</strong>: Earlie Schleusner is the top-performing sales rep, generating over <strong>$1 million</strong> in revenue, followed by Tia Amato and Vernita Plump. These top 5 sales reps are responsible for a significant portion of the company’s sales revenue.</li><li><strong>Decision</strong>: The company may consider incentivizing or promoting these top performers, or analyzing their sales strategies to replicate success across the sales team.</li><li><strong>Total Number of Orders by Region</strong>:</li><li><strong>Insight</strong>: The <strong>Northeast region</strong> leads in terms of total orders with <strong>2,357 orders</strong>, followed by the Southeast. The Midwest has the fewest orders, at <strong>897</strong>.</li><li><strong>Decision</strong>: There could be an opportunity to boost marketing or sales efforts in the Midwest region to increase order volume and potentially grow revenue.</li><li><strong>Product Type with the Most Orders</strong>:</li><li><strong>Insight</strong>: <strong>Standard paper</strong> is by far the most popular product, generating <strong>1,938,346 orders</strong>, followed by <strong>Gloss</strong> and <strong>Poster</strong>.</li><li><strong>Decision</strong>: The company might want to focus on optimizing inventory and marketing strategies for standard paper, as it generates the most demand.</li><li><strong>Average Order Value by Product Type</strong>:</li><li><strong>Insight</strong>: The <strong>Standard paper</strong> has the highest average order value at <strong>$1,399.4</strong>, while <strong>Poster</strong> has the lowest at <strong>$850.1</strong>.</li><li><strong>Decision</strong>: While posters generate fewer orders and have a lower average order value, the company may consider bundling or promotional offers to increase revenue from poster sales.</li><li><strong>Region with the Highest Revenue</strong>:</li><li><strong>Insight</strong>: The <strong>Northeast</strong> region generates the highest revenue at <strong>$7,744,405.36</strong>, followed by the Southeast and West. The Midwest has the lowest revenue at <strong>$3,013,486.51</strong>.</li><li><strong>Decision</strong>: Given the disparity, the company could focus on improving revenue generation in the Midwest by increasing customer acquisition efforts or offering region-specific promotions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f27be4254bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Market Size Analysis of Electric Vehicles Using Python]]></title>
            <link>https://medium.com/@emmanuelwale83/market-size-analysis-of-electric-vehicles-using-python-a07c99f9f770?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/a07c99f9f770</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 19:39:42 GMT</pubDate>
            <atom:updated>2024-09-25T19:39:42.663Z</atom:updated>
            <content:encoded><![CDATA[<h4>By ASHOGBON<strong><em> ADEWALE</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CiACsZ6bLqLdGaqW.jpg" /></figure><h3>Introduction</h3><p>As a data analyst, my goal is to assist stakeholders in understanding the market for electric vehicles (EVs). This project involves analyzing a comprehensive dataset that provides insights into EV registrations. The dataset is country-specific to the United States, with a notable concentration of data from Washington State. This allows for both a broad analysis of national trends and a detailed examination of regional patterns within Washington State.</p><p>By exploring this dataset, we aim to uncover trends in EV adoption, assess historical growth, and forecast future registrations. This information is crucial for stakeholders, including policymakers, automotive manufacturers, and market strategists, to make informed decisions that support the growth and development of the EV market.</p><h3><strong>About Dataset</strong></h3><h4>Source</h4><p>The dataset used for this analysis is sourced from <a href="https://statso.io/market-size-of-evs-case-study/#google_vignette">here.</a> It contains detailed information about electric vehicle (EV) registrations in the United States, with a particular focus on Washington State, and covers registrations from 1997 to 2024 (March 2024).</p><h4>Description</h4><p>The provided dataset contains the following columns, each representing different aspects of the electric vehicle (EV) population in the United States:</p><ul><li><strong>VIN (1–10):</strong> Partial Vehicle Identification Number.</li><li><strong>County:</strong> The county in which the vehicle is registered.</li><li><strong>City:</strong> The city in which the vehicle is registered.</li><li><strong>State:</strong> The state in which the vehicle is registered. It appears that this dataset may be focused on Washington (WA) state.</li><li><strong>Postal Code:</strong> The postal code where the vehicle is registered.</li><li><strong>Model Year:</strong> The year of the vehicle model.</li><li><strong>Make:</strong> The manufacturer of the vehicle.</li><li><strong>Model:</strong> The model of the vehicle.</li><li><strong>Electric Vehicle Type:</strong> The type of electric vehicle, e.g., Battery Electric Vehicle (BEV).</li><li><strong>Clean Alternative Fuel Vehicle (CAFV) Eligibility:</strong> Eligibility status for clean alternative fuel vehicle programs.</li><li><strong>Electric Range:</strong> The maximum range of the vehicle on a single charge (in miles).</li><li><strong>Base MSRP:</strong> The Manufacturer’s Suggested Retail Price.</li><li><strong>Legislative District:</strong> The legislative district where the vehicle is registered.</li><li><strong>DOL Vehicle ID:</strong> Department of Licensing Vehicle Identification.</li><li><strong>Vehicle Location:</strong> Geographic coordinates of the vehicle location.</li><li><strong>Electric Utility:</strong> The electric utility service provider for the vehicle’s location.</li><li><strong>2020 Census Tract:</strong> The census tract for the vehicle’s location.</li></ul><h4>Usage</h4><p>This dataset is used to analyze trends in EV registrations, assess historical growth patterns, and forecast future registrations. The insights derived from this analysis can help stakeholders make informed decisions regarding the promotion and support of electric vehicles.</p><h3>Data Importation and Cleaning</h3><h4>Data Importation</h4><p>First, we import the necessary libraries and load the dataset into a Pandas DataFrame.</p><pre># Import necesarry packages <br>import pandas as pd<br>import numpy as np<br><br># Load the dataset<br><br>ev_df= pd.read_csv(r&quot;C:\Users\USER\Downloads\new ev_pop\Electric_Vehicle_Population_Data.csv&quot;)<br>print(ev_df.head())<br></pre><pre>VIN (1-10)     County       City State  Postal Code  Model Year   Make  \<br>0  5YJYGDEE1L       King    Seattle    WA      98122.0        2020  TESLA   <br>1  7SAYGDEE9P  Snohomish    Bothell    WA      98021.0        2023  TESLA   <br>2  5YJSA1E4XK       King    Seattle    WA      98109.0        2019  TESLA   <br>3  5YJSA1E27G       King   Issaquah    WA      98027.0        2016  TESLA   <br>4  5YJYGDEE5M     Kitsap  Suquamish    WA      98392.0        2021  TESLA   <br><br>     Model           Electric Vehicle Type  \<br>0  MODEL Y  Battery Electric Vehicle (BEV)   <br>1  MODEL Y  Battery Electric Vehicle (BEV)   <br>2  MODEL S  Battery Electric Vehicle (BEV)   <br>3  MODEL S  Battery Electric Vehicle (BEV)   <br>4  MODEL Y  Battery Electric Vehicle (BEV)   <br><br>   Clean Alternative Fuel Vehicle (CAFV) Eligibility  Electric Range  \<br>0            Clean Alternative Fuel Vehicle Eligible             291   <br>1  Eligibility unknown as battery range has not b...               0   <br>2            Clean Alternative Fuel Vehicle Eligible             270   <br>3            Clean Alternative Fuel Vehicle Eligible             210   <br>4  Eligibility unknown as battery range has not b...               0   <br><br>   Base MSRP  Legislative District  DOL Vehicle ID  \<br>0          0                  37.0       125701579   <br>1          0                   1.0       244285107   <br>2          0                  36.0       156773144   <br>3          0                   5.0       165103011   <br>4          0                  23.0       205138552   <br><br>                Vehicle Location  \<br>0   POINT (-122.30839 47.610365)   <br>1  POINT (-122.179458 47.802589)   <br>2   POINT (-122.34848 47.632405)   <br>3   POINT (-122.03646 47.534065)   <br>4   POINT (-122.55717 47.733415)   <br><br>                                Electric Utility  2020 Census Tract  <br>0   CITY OF SEATTLE - (WA)|CITY OF TACOMA - (WA)       5.303301e+10  <br>1                         PUGET SOUND ENERGY INC       5.306105e+10  <br>2   CITY OF SEATTLE - (WA)|CITY OF TACOMA - (WA)       5.303301e+10  <br>3  PUGET SOUND ENERGY INC||CITY OF TACOMA - (WA)       5.303303e+10  <br>4                         PUGET SOUND ENERGY INC       5.303594e+10</pre><h3>Data Cleaning</h3><h4>Correcting Data Types and Column names</h4><pre># Change the name of the &quot;VIN (1-10)&quot; column to &quot;Vin&quot;<br>ev_df.rename(columns={&#39;VIN (1-10)&#39;: &#39;Vin&#39;}, inplace=True)<br># Change the name of the &quot;Clean Alternative Fuel Vehicle (CAFV) Eligibility &quot; column to &quot;CAFV&quot;<br>ev_df.rename(columns={&#39;Clean Alternative Fuel Vehicle (CAFV) Eligibility&#39;:&#39;CAFV&#39;},inplace=True)<br># Change the name of the &quot;Base MSRP&quot; column to &quot;VehiclePrice&quot;<br>ev_df.rename(columns={&#39;Base MSRP&#39;:&#39;VehiclePrice&#39;},inplace=True)<br># Assigning appropriate datatypes to the columns<br>ev_df[&#39;Postal Code&#39;]=ev_df[&#39;Postal Code&#39;].astype(str)<br>ev_df[&#39;Model Year&#39;] = pd.to_datetime(ev_df[&#39;Model Year&#39;], format=&#39;%Y&#39;)<br>ev_df[&#39;CAFV&#39;] = ev_df[&#39;CAFV&#39;].astype(&#39;category&#39;)<br>ev_df[&#39;DOL Vehicle ID&#39;]=ev_df[&#39;DOL Vehicle ID&#39;].astype(str)<br>ev_df[&#39;2020 Census Tract&#39;]=ev_df[&#39;2020 Census Tract&#39;].astype(str)<br>#Remapping <br># Define a mapping dictionary to simplify the categories<br>mapping = {&#39;Clean Alternative Fuel Vehicle Eligible&#39;: &#39;Eligible&#39;,<br>&#39;Eligibility unknown as battery range has not been researched&#39;: &#39;Unknown&#39;,<br>&#39;Not eligible due to low battery range&#39;: &#39;Not Eligible&#39;}<br><br># Map the values in the &quot;CAFV&quot; column to the simplified categories<br>ev_df[&#39;CAFV&#39;] = ev_df[&#39;CAFV&#39;].map(mapping)<br><br># Convert the &quot;CAFV&quot; column to categorical datatype<br>ev_df[&#39;CAFV&#39;] = ev_df[&#39;CAFV&#39;].astype(&#39;category&#39;)<br><br># Verify the unique values<br>print(ev_df[&#39;CAFV&#39;].unique())<br></pre><h4>Handling Missing Values</h4><p>We check for missing values in the dataset and handle them appropriately.</p><pre># Check for missing values<br>missing_values = ev_df.isnull().sum()<br>print(missing_values)<br><br><br>ev_df = ev_df.dropna<br><br>print(ev_df.isnull().sum())</pre><h4>Removing Duplicates</h4><p>We remove any duplicate rows to ensure data integrity.</p><pre># Remove duplicate rows<br>ev_df.drop_duplicates(inplace=True)</pre><h3>Exploratory Data Analysis (EDA)</h3><p>For the task of market size analysis for electric vehicles, we can explore the following areas:</p><ol><li><strong>EV Adoption Over Time:</strong> Analyze the growth of the EV population by model year.</li><li><strong>Geographical Distribution:</strong> Understand where EVs are most commonly registered (e.g., by county or city).</li><li><strong>EV Types:</strong> Breakdown of the dataset by electric vehicle type (BEV, etc.).</li><li><strong>Make and Model Popularity:</strong> Identify the most popular makes and models among the registered EVs.</li><li><strong>Electric Range Analysis:</strong> Analyze the electric range of vehicles to see how EV technology is progressing.</li><li><strong>Estimated Growth in Market Size:</strong> Analyze and find the estimated growth in the market size of electric vehicles.</li></ol><h3>1. EV Adoption Over Time</h3><p>Let’s start with analyzing the <strong>EV Adoption Over Time</strong> by visualizing the number of EVs registered by model year. It will give us an insight into how the EV population has grown over the years:</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.set_style(&quot;whitegrid&quot;)<br><br># EV Adoption Over Time<br>plt.figure(figsize=(12, 6))<br>ev_adoption_by_year = ev_df[&#39;Model Year&#39;].value_counts().sort_index()<br>sns.barplot(x=ev_adoption_by_year.index, y=ev_adoption_by_year.values, palette=&quot;viridis&quot;)<br>plt.title(&#39;Electric Car Registrations by Model Year&#39;)<br>plt.xlabel(&#39;Model Year&#39;)<br>plt.ylabel(&#39;Number of  Registrations&#39;)<br>plt.xticks(rotation=45)<br>plt.tight_layout()<br>plt.show()<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA1Mh5u8kOgOkSuIbTVLHw.png" /></figure><h4>Insight:</h4><p>From the above chart, it is obvious that the adoption of electric vehicles has seen a dramatic increase over the past decade, particularly in the last few years. This suggests a strong upward trajectory in the acceptance and integration of EVs into the market. The sharp rise in registrations post-2017 underscores the impact of technological advancements, better infrastructure, and supportive policies on driving EV adoption. Despite the partial data for 2024, the continued growth pattern suggests that the market for EVs is poised for further expansion.</p><h3>2. Geographical Distribution</h3><p>To understand where EVs are most commonly registered, we’ll analyze the data by city and visualize the top 5 cities with the highest number of EV registrations.</p><p>First, let’s prepare the data by grouping it by city and then identifying the top 5 cities with the highest registrations.</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Group by City and count registrations<br>registrations_by_city = ev_df.groupby(&#39;City&#39;).size().sort_values(ascending=False)<br><br># Get the top 5 cities<br>top_5_cities = registrations_by_city.head(5)<br>print(top_5_cities)<br><br># Convert the Series to a DataFrame for Seaborn<br>top_5_cities_df = top_5_cities.reset_index()<br>top_5_cities_df.columns = [&#39;City&#39;, &#39;Registrations&#39;]<br><br># Plot the top 5 cities using a horizontal bar chart<br>plt.figure(figsize=(10, 6))<br>sns.barplot(x=&#39;Registrations&#39;, y=&#39;City&#39;, data=top_5_cities_df, palette=&#39;viridis&#39;)<br>plt.title(&#39;Top 5 Cities by EV Registrations&#39;)<br>plt.xlabel(&#39;Number of Registrations&#39;)<br>plt.ylabel(&#39;City&#39;)<br>plt.grid(axis=&#39;x&#39;, linestyle=&#39;--&#39;, alpha=0.7)<br>plt.tight_layout()<br>plt.show()</pre><pre>City<br>Seattle      29447<br>Bellevue      8931<br>Redmond       6478<br>Vancouver     6193<br>Bothell       5863<br>dtype: int64</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*RVpmRjCdpcinuHgJfrrvOQ.png" /><figcaption><strong>Seattle’s Dominance</strong></figcaption></figure><p>The output shows that Seattle leads the way in electric vehicle registrations with 29,447 vehicles, significantly higher than the next cities on the list. Bellevue follows with 8,931 registrations, and Redmond with 6,478. Vancouver and Bothell also show strong adoption, with 6,193 and 5,863 registrations, respectively.</p><ul><li>Seattle’s Dominance: Seattle’s high number of registrations indicates a strong market presence for EVs, likely driven by supportive policies, infrastructure, and a population with higher environmental awareness.</li><li>Regional Trends: The concentration of EV registrations in these cities suggests regional trends, potentially influenced by urban development, the availability of charging stations, and economic factors.</li><li>Market Opportunities: For stakeholders, these cities represent key markets for EV promotion and infrastructure development. The data also provides a benchmark for other cities aiming to increase their EV adoption rates.</li></ul><h3>3. EV Types</h3><p>Now let’s explore the types of EVs being registered and see how many of each type are registered. Understanding the breakdown between different EV types, such as Battery Electric Vehicles (BEVs) and Plug-in Hybrid Electric Vehicles (PHEVs), can provide insights into consumer preferences and the adoption patterns of purely electric versus hybrid electric solutions. This analysis will help us understand which types of EVs are gaining traction in the market and inform strategies for promoting the adoption of various electric vehicle technologies.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>ev_type_counts = ev_df[&#39;Electric Vehicle Type&#39;].value_counts()<br><br># Plot the distribution of EV types<br>plt.figure(figsize=(10, 6))<br>sns.barplot(x=ev_type_counts.values, y=ev_type_counts.index, palette=&#39;viridis&#39;)<br>plt.title(&#39;Distribution of EV Types&#39;)<br>plt.xlabel(&#39;Number of Registrations&#39;)<br>plt.ylabel(&#39;EV Type&#39;)<br>plt.grid(axis=&#39;x&#39;, linestyle=&#39;--&#39;, alpha=0.7)<br><br># Annotate bars with the counts<br>for index, value in enumerate(ev_type_counts.values):<br>    plt.text(value, index, str(value), va=&#39;center&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Hn_S7tElR9RzlDO6uzT25g.png" /></figure><p>The above graph shows that BEVs are more popular or preferred over PHEVs among the electric vehicles registered in the United State.</p><h4>3. Make and Model Popularity</h4><p>Let’s identify the most popular makes and models among the registered EVs. So as to know consumers’ preference</p><p>By Make</p><pre># Top 10 makes by EV registrations<br>top_makes = ev_df[&#39;Make&#39;].value_counts().head(10)<br>print(top_makes)<br><br># Plot the top 10 makes by EV registrations<br>plt.figure(figsize=(12, 6))<br>top_makes.plot(kind=&#39;bar&#39;, color=&#39;skyblue&#39;)<br>plt.title(&#39;Top 10 Makes by EV Registrations&#39;)<br>plt.xlabel(&#39;Make&#39;)<br>plt.ylabel(&#39;Number of Registrations&#39;)<br>plt.xticks(rotation=45)<br>plt.grid(axis=&#39;y&#39;, linestyle=&#39;--&#39;, alpha=0.7)<br>plt.tight_layout()<br>plt.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36FcN38Rz0p7py17v4ziBg.png" /><figcaption><strong>Dominance of TESLA</strong></figcaption></figure><p>The above chart shows</p><ol><li>Tesla’s Dominance: Tesla leads significantly with 79,659 registrations, indicating its strong market presence and brand dominance in the EV sector.</li><li>Significant Gap: The second highest, Nissan, has 13,998 registrations, highlighting the large gap between Tesla and other brands.</li><li>Established Brands: Traditional automakers like Nissan, Chevrolet, Ford, BMW, Toyota, and Hyundai show strong participation in the EV market.</li><li>International Interest: Brands like Kia, Volkswagen, and Hyundai reflect a diverse international competition in the U.S. EV market.</li><li>Emerging Contenders: Brands such as Kia and Jeep have successfully entered the EV market, demonstrating growing consumer acceptance.</li></ol><p>By Model</p><p>Now let’s drill down to the most popular model within these top manufacturers to get an understanding of consumer preference .</p><pre># Top 10 models by EV registrations<br>top_models = ev_df[&#39;Model&#39;].value_counts().head(10)<br><br><br># Plot the top 10 models by EV registrations<br>plt.figure(figsize=(12, 6))<br>sns.barplot(x=top_models.values, y=top_models.index, palette=&#39;viridis&#39;)<br>plt.title(&#39;Top 10 Models by EV Registrations&#39;)<br>plt.xlabel(&#39;Model&#39;)<br>plt.ylabel(&#39;Number of Registrations&#39;)<br>plt.grid(axis=&#39;y&#39;, linestyle=&#39;--&#39;, alpha=0.7)<br><br># Annotate bars with the counts<br>for index, value in enumerate(top_models.values):<br>    plt.text(value, index, str(value), va=&#39;center&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgRqMm8efxjEZ_64fJWlTA.png" /></figure><p>Tesla models are the most registered EVs, indicating strong market leadership.</p><ul><li>Nissan and Chevrolet have significant representation with popular models.</li><li>Newer models from Volkswagen, Jeep, and Ford show increasing market acceptance.</li></ul><h4>4. Estimated Growth in Market Size:</h4><p>Now let’s analyze and find the estimated growth in the market size of electric vehicles. To do this, I want to first check the trend of the dataset</p><p>Using Moving Averages to check the Trends of the Dataset.</p><p>Moving averages are particularly useful for identifying the overall direction of the trend by averaging out the noise from the data and they also help to highlight long-term trends and mitigate the effect of short-term fluctuations.</p><p>Let’s count the number of EVs registered every year:</p><pre># calculate the number of EVs registered each year<br>ev_registration_counts = ev_data[&#39;Model Year&#39;].value_counts().sort_index()<br>ev_registration_counts</pre><pre>1997        1<br>1998        1<br>1999        5<br>2000        7<br>2002        2<br>2003        1<br>2008       19<br>2010       23<br>2011      775<br>2012     1614<br>2013     4399<br>2014     3496<br>2015     4826<br>2016     5469<br>2017     8534<br>2018    14286<br>2019    10913<br>2020    11740<br>2021    19063<br>2022    27708<br>2023    57519<br>2024     7072<br>Name: Model Year, dtype: int64</pre><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br><br><br># Convert &#39;Model Year&#39; column to datetime format<br>ev_df[&#39;Model Year&#39;] = pd.to_datetime(ev_df[&#39;Model Year&#39;], format=&#39;%Y&#39;)<br><br># Group by &#39;Model Year&#39; and count the number of vehicles<br>yearly_counts = ev_df.groupby(ev_df[&#39;Model Year&#39;].dt.year).size().reset_index(name=&#39;Registrations&#39;)<br><br># Calculate moving average (adjust window size as needed)<br>window_size = 5 # Example window size<br>yearly_counts[&#39;Moving Average&#39;] = yearly_counts[&#39;Registrations&#39;].rolling(window=window_size).mean()<br>print(yearly_counts)<br><br># Plot the original data and the moving average<br>plt.figure(figsize=(12, 6))<br><br>plt.plot(yearly_counts[&#39;Model Year&#39;], yearly_counts[&#39;Moving Average&#39;], label=f&#39;{window_size}-Year Moving Average&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;EV Registrations with Moving Average&#39;)<br>plt.xlabel(&#39;Model Year&#39;)<br>plt.ylabel(&#39;Registrations&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJqHqUGKNGS_gMevJxjP2g.png" /><figcaption><strong>EV registrations and Moving Averages(The moving averages indicate a strong upward trend in EV registrations.)</strong></figcaption></figure><p>The above chart provides a clear picture of the increasing trend in electric vehicle (EV) registrations over the past few years. Here are the key insights:</p><ol><li>Significant Growth in EV Registrations:</li></ol><p>From 2021 to 2022, EV registrations saw a substantial increase from 19,063 to 27,708, indicating a year-over-year growth of approximately 45.3%.</p><ul><li>The growth was even more pronounced from 2022 to 2023, with registrations more than doubling from 27,708 to 57,519, reflecting a remarkable year-over-year growth of 107.7%.</li></ul><p>2. Partial Data for 2024:</p><p>. The data for 2024 shows only 7,072 registrations, which covers just up to March 2024. This suggests that if the trend from previous years continues, the final number for 2024 could be significantly higher by the end of the year.</p><ul><li>Given the previous growth patterns, a simple projection for the full year of 2024 can be made. If we assume the registrations continue at a similar rate for the remaining months, we can estimate the full-year figure. For example, if 7,072 represents one quarter, then a rough estimate for the entire year would be around 28,288 registrations (7,072 * 4), assuming steady growth.</li></ul><p>Conclusion:</p><p>The data clearly indicates a rapid adoption of electric vehicles in recent years, with a significant spike in registrations from 2022 to 2023. While the 2024 data is incomplete, the early figures suggest continued strong growth. This trend highlights the increasing acceptance and market penetration of electric vehicles, likely driven by technological advancements, increased environmental awareness, and supportive policies.</p><p>To forecast the number of electric vehicle (EV) registrations for 2024 and the next five years using the Compound Annual Growth Rate (CAGR), we can follow these steps:</p><p>let’s use the full range of registration data from 1997 to 2023 to calculate the Compound Annual Growth Rate (CAGR) and forecast the registrations for 2024 and the next five years.</p><p>Here’s the code to perform these tasks:</p><ol><li>Calculate the CAGR using the registration data from 1997 to 2023.</li><li>Use this CAGR to forecast future registrations up to 2029.</li></ol><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Registration data from 1997 to 2023<br>data = {<br>    &#39;Model Year&#39;: [1997, 1998, 1999, 2000, 2002, 2003, 2008, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023],<br>    &#39;Registrations&#39;: [1, 1, 5, 7, 2, 1, 20, 23, 775, 1618, 4409, 3509, 4844, 5483, 8562, 14323, 10940, 11768, 19132, 27776, 57587]<br>}<br><br># Convert to DataFrame<br>df = pd.DataFrame(data)<br><br># Calculate CAGR<br>beginning_value = df[&#39;Registrations&#39;].iloc[0]  # 1997 value<br>ending_value = df[&#39;Registrations&#39;].iloc[-1]   # 2023 value<br>n = len(df) - 1  # Number of years (2023 - 1997)<br><br>cagr = (ending_value / beginning_value) ** (1 / n) - 1<br><br>print(f&quot;CAGR: {cagr:.4f}&quot;)<br><br># Forecasting the next 5 years including 2024<br>forecast_years = [2024, 2025, 2026, 2027, 2028, 2029]<br>forecast_registrations = []<br><br># Use the last known full year registration as the starting point for forecasting<br>last_known_value = df[&#39;Registrations&#39;].iloc[-1]<br><br>for year in forecast_years:<br>    forecast_value = last_known_value * (1 + cagr)<br>    forecast_registrations.append(round(forecast_value))<br>    last_known_value = forecast_value<br><br># Create a DataFrame for the forecasted values<br>forecast_df = pd.DataFrame({<br>    &#39;Model Year&#39;: forecast_years,<br>    &#39;Registrations&#39;: forecast_registrations<br>})<br><br># Display the forecasted values<br>print(forecast_df)<br><br># Plotting the actual and forecasted values<br>plt.figure(figsize=(12, 6))<br><br># Actual values<br>plt.plot(df[&#39;Model Year&#39;], df[&#39;Registrations&#39;], label=&#39;Actual EV Registrations&#39;, marker=&#39;o&#39;, color=&#39;blue&#39;)<br><br># Forecasted values<br>plt.plot(forecast_df[&#39;Model Year&#39;], forecast_df[&#39;Registrations&#39;], label=&#39;Forecasted EV Registrations&#39;, linestyle=&#39;--&#39;, marker=&#39;x&#39;, color=&#39;red&#39;)<br><br># Plot details<br>plt.title(&#39;EV Registrations with Forecast&#39;)<br>plt.xlabel(&#39;Model Year&#39;)<br>plt.ylabel(&#39;Registrations&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6tuitWwB9VA8q7sTdKN4A.png" /></figure><ul><li>CAGR: The Compound Annual Growth Rate (CAGR) from 1997 to 2023 is calculated to be 0.7299 (or 72.99%). This high growth rate indicates a rapid increase in electric vehicle (EV) registrations over the past years.</li></ul><h4>Forecasted Registrations</h4><p>Based on the CAGR of 0.7299, the forecasted EV registrations for the next five years are as follows:</p><ul><li>2024: 99,619 registrations</li><li>2025: 172,328 registrations</li><li>2026: 298,108 registrations</li><li>2027: 515,691 registrations</li><li>2028: 892,084 registrations</li><li>2029: 1,543,198 registrations</li></ul><h4>Visualization Insights</h4><ul><li>Actual Data Trend: From 1997 to 2023, there has been a noticeable upward trend in EV registrations, particularly accelerating after 2011.</li><li>Forecasted Growth: The forecasted values show an exponential increase in EV registrations, suggesting that if the current growth trend continues, the market size for EVs will expand significantly in the coming years.</li><li>Market Potential: The substantial growth in forecasted values reflects the potential for a booming EV market, driven by factors such as technological advancements, policy incentives, increasing consumer awareness, and infrastructure improvements.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a07c99f9f770" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing Big Data with SQL]]></title>
            <link>https://medium.com/@emmanuelwale83/analyzing-big-data-with-sql-b99565d043b8?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/b99565d043b8</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 09:13:41 GMT</pubDate>
            <atom:updated>2023-07-04T09:13:41.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*sxzvOZtkN1ekKTpN.png" /></figure><p>This article provides my solution to the Railway industry case study 1 using Impala. Dataset gotten from<strong> </strong><a href="https://www.coursera.org/specializations/cloudera-big-data-analysis-sql"><strong>CLOUDERA Big Data Analysis Specialization</strong></a> in the “Analysis of Big Data with SQL” course offered by Cloudera. Dataset stored in Hadoop Distributed File System, HDFS.</p><p>I played the role of a data analyst for a railway company that plans to disrupt the airline industry by building an underground high-speed passenger rail tunnel.</p><h3>PROBLEM STATEMENT</h3><blockquote><em>A Railway company needs help to decide which two major United States airports this tunnel should connect using the </em><strong><em>flight</em></strong><em> and </em><strong><em>planes</em></strong><em> datasets in the </em><strong><em>fly</em></strong><em> database. The distance between the airports must be within a specified range, and the airports must have a large volume of air travelers flying between them in both directions. The company believes that these air travelers can be persuaded to switch to high-speed rail because of frustratingly long flight delays.</em></blockquote><h3>FACTORS TO CONSIDER WHEN PERFORMING THIS TASK</h3><p>· pairs of airports should be between <strong>300</strong> and <strong>400</strong> miles apart</p><p>· had at least <strong>5,000 </strong>(five thousand) flights per year on average <em>in each direction</em> between them</p><p>· identify which one of these pairs of airports has largest total number of seats on the planes that flew between them</p><h3>DATA EXPLORATION</h3><p>On exploring the plane and flights datasets, I observed a relationship which I could use to JOIN the two tables. I have presented the schemas for the flights datasets and the planes datasets</p><h3>ENTITY RELATIONSHIP DIAGRAM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*uhwwfOOZItoqvbT6.jpeg" /></figure><h3>Data Analysis</h3><p>After going through the metrics to be considered, I identified this route by running the following SELECT statement using Impala on the Hadoop User Experience (HUE) using a Virtual Machine (VM): The dataset has already been loaded on the File system.</p><p>First I made my fly database my current/active database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*CMjkKWbhOmdqYjfE.jpeg" /></figure><p>The SQL code used to proffer a solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*iVW-V_NRxFl2FWU9.jpeg" /></figure><h3>Results</h3><p>From the above query, I have tabled the result and I recommend the following tunnel route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*FpEnt_t8PPSWYbiv.jpeg" /></figure><h3>Recommendations</h3><p>· From the analysis done above, it is recommended to build a underground high-speed passenger rail tunnel going from airport SFO (<strong>San Francisco)</strong> to airport LAX (<strong>Los Angeles)</strong> and vice versa. This is because from the result of the query, they have the highest average number of flights per year and they have a very high average passenger capacity per year.</p><p>· Also from the analysis, the next recommended airport where the underground high-speed passenger rail tunnel could be built is at airport PHX (<strong>Phoenix</strong>) and airport LAX (<strong>Los Angeles</strong>). They have the second highest average number of flights per year and their average passenger per year is pretty high as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b99565d043b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Murder Mystery- Exploratory Data Analysis]]></title>
            <link>https://medium.com/@emmanuelwale83/sql-murder-mystery-exploratory-data-analysis-123720d5df35?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/123720d5df35</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 09:09:04 GMT</pubDate>
            <atom:updated>2023-07-04T09:09:04.084Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL is a powerful tool for data analysis and can be used to solve crimes.</p><p>As a data analyst detective, I find great excitement in delving into data and uncovering hidden answers, much like a detective on a case. In the city of SQL, a crime (murder) occurred on January 15, 2018.</p><p>Tasked with solving the murder, I employed my analytical skills to identify the culprit behind this heinous act. Below, you will find further details regarding the individual responsible for the crime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*t8PRc0mXH9zMQ4NS.png" /></figure><h3>TASK</h3><p>A crime has taken place and the detective needs your help. The detective gave you the crime scene report, but you somehow lost it. You vaguely remember that the crime was a murder that occurred sometime on Jan.15, 2018, and that it took place in SQL City. Start by retrieving the corresponding crime scene report from the police department’s database.</p><p>Link to Database: s<a href="https://drive.google.com/drive/folders/1SLlSSzIqhu9m4p8HmoJYjn5X_GTYdDsf?usp=share_link">ql murder_mystrey_database</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*q4Z80YxOAg2fxhS_.png" /></figure><p>Database Schema</p><h3>Exploring the Database Structure</h3><p><strong>Upload the database and preview the tables</strong></p><p>Firstly, I opened the SQLiteOnline website and uploaded the sql-murder-mystery.db file. Next, run the following SQL query to view all the tables in the database.</p><pre>SELECT name FROM sqlite_master WHERE type=&#39;table&#39;;</pre><p><strong>Tables</strong></p><ul><li>crime_scene_report</li><li>drivers_license</li><li>person</li><li>facebook_event-checkin</li><li>interview</li><li>get_fit_now_check_in</li><li>income</li><li>solution (this is to verify the answer)</li></ul><h3>Finding the murderer</h3><p>Checking the crime_scene_report table for a murder case that was committed in SQL City on January 15th, 2018.</p><pre>--Retrieving the corresponding crime scene report<br>SELECT * FROM crime_scene_report<br>WHERE date=20180115 <br>     AND city=&#39;SQL City&#39;<br>     and type=&#39;murder&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*ls_VcVOEbCluk7I1.png" /></figure><h3>Crime scene description</h3><blockquote><em>Security footage shows that there were 2 witnesses:<br>The first witness lives at the last house on “Northwestern Dr”.</em></blockquote><blockquote><em>The second witness, Annabel, lives somewhere on “Franklin Ave”.</em></blockquote><pre>SELECT * FROM person<br>WHERE (address_street_name LIKE &#39;Northwestern%&#39;<br>       OR (name LIKE &#39;Annabel%&#39; and address_street_name =&#39;Franklin Ave&#39; ))<br>ORDER BY address_number Desc;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*aL87XUwaDEsCHxKc.png" /></figure><h3>The witness</h3><blockquote><em>Morty Schapiro with id 14887 has the last house number (4919) on Northwestern Dr</em></blockquote><blockquote><em>Annabel Miller with id 16371 and address_street_name Franklin Ave</em></blockquote><p><strong>Using the referential details to find out the witness’s testimonials.</strong></p><pre>SELECT * FROM interview<br>WHERE (person_id =&#39;16371&#39; OR person_id= &#39;14887&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*iUoBxWaJZnhlQI6h.png" /></figure><h3>Witness Interview transcript</h3><blockquote><em>Morty Schapiro (id 14887) Transcript Interview: “I heard a gunshot and then saw a man run out. He had a “Get Fit Now Gym” bag. The membership number on the bag started with “48Z”. Only gold members have those bags. The man got into a car with a plate that included “H42W”.</em></blockquote><blockquote><em>Annabel Miller (id 16371) Transcript Interview:</em><strong><em> </em></strong><em>“I saw the murder happen, and I recognized the killer from my gym when I was working out last week on January the 9th”.</em></blockquote><h3>The leads</h3><p>Following Annabel Miller’s and Morty Schapiro’s Testimony</p><blockquote><strong><em>1st lead</em></strong></blockquote><blockquote><em>Checking people that were at the gym on </em><strong><em>January 9th, 2018</em></strong><em> and with membership_id like ‘</em><strong><em>48Z’ </em></strong><em>and membership_status </em><strong><em>Gold</em></strong></blockquote><pre>SELECT * FROM get_fit_now_check_in<br>WHERE check_in_date=20180109 And membership_id LIKE &#39;48Z%&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*FCbX1g2Vo9nEsveB.png" /></figure><p>Two persons with membership_id like ‘48Z’ came to the gym on January 9th, 2018.</p><pre>SELECT * FROM get_fit_now_member<br>WHERE id =(&#39;48Z7A&#39; OR id=&#39;48Z55&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*uRfnkRbc5BwNJCCs.png" /></figure><blockquote><em>Two suspects were found from the 1st lead: Jeremy Bowers and Joe Germuska</em></blockquote><blockquote><strong><em>2nd lead</em></strong></blockquote><blockquote><em>The man got into a car with a plate that included </em><strong><em>“H42W”</em></strong></blockquote><p>Merging the person and the drivers_license table to continue the investigation</p><pre>Select * From person<br>FULL JOIN drivers_license<br>ON person.license_id=drivers_license.id<br>Where plate_number like &#39;%H42W%&#39;<br>Order by plate_number;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*C7O0x_qGQfvpkwXE.png" /></figure><p>The witness said that the murderer is a ‘man’ (male), which removes Maxine Whitely from the suspect list.</p><blockquote><em>Two suspects were found from the 2nd lead: Jeremy Bowers and Turshar Chandra.</em></blockquote><p><strong>Jeremy Bowers</strong> is on the 1st and 2nd lead. Is he the murderer?</p><p>Verifying using the solution table.</p><pre>INSERT into solution Values (1, &#39;Jeremy Bowers&#39;);</pre><pre>SELECT value from solution;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*P_8BqA21l0sHMUZs.png" /></figure><blockquote><em>Congrats, you found the murderer! But wait, there’s more… If you think you’re up for a challenge, try querying the interview transcript of the murderer to find the real villain behind this crime. If you feel especially confident in your SQL skills, try to complete this final step with no more than 2 queries. Use this same INSERT statement with your new suspect to check your answer.</em></blockquote><h3>The Murderer is “Jeremy Bowers”, But who sent him?</h3><p>Further investigation to find the reason behind the murder</p><pre>select person.id, person.name, interview. transcript<br>from person<br>join interview on person.id=interview.person_id<br>where name=&#39;Jeremy Bowers&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*-Y_q3i_HPXoI6wLA.png" /></figure><blockquote><strong><em>Jeremy Bowers Transcript</em></strong></blockquote><blockquote><em>“I was hired by a </em><strong><em>woman</em></strong><em> with a lot of </em><strong><em>money</em></strong><em>. I don’t know her name but I know she’s around </em><strong><em>5&#39;5” (65&quot;) or</em></strong><em> </em><strong><em>5&#39;7&quot; (67&quot;).</em></strong><em> She has </em><strong><em>red hair</em></strong><em> and she drives a </em><strong><em>Tesla Model S.</em></strong><em> I know that she attended the </em><strong><em>SQL Symphony Concert 3 times</em></strong><em> in </em><strong><em>December 2017”.</em></strong></blockquote><p>Finding the Villain</p><pre>SELECT person.name, drivers_license.age, drivers_license.height,drivers_license.hair_color, drivers_license.gender,<br>drivers_license.car_make,facebook_event_checkin.event_name,facebook_event_checkin.date<br>From person <br>Join drivers_license On person.license_id=drivers_license.id<br>Join facebook_event_checkin On person.id=facebook_event_checkin.person_id<br>Where drivers_license.gender=&#39;female&#39;<br>and drivers_license.height BETWEEN 65 and 67<br>And drivers_license.hair_color=&#39;red&#39;<br>And drivers_license.car_make=&#39;Tesla&#39;<br>And facebook_event_checkin.event_name=&#39;SQL Symphony Concert&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*-gT2lrNYmnMnUao-.png" /></figure><p><strong>Miranda Priestly </strong>is the villain, using the solution table to verify.</p><pre>INSERT into solution Values (1, &#39;Miranda Priestly&#39;);</pre><pre>SELECT value from solution;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*AYNIdJcdFjyWzC62.png" /></figure><p>Confirmed!<strong> Miranda Priestly</strong> hired <strong>Jeremy Bowers </strong>to murder so they should be arrested.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=123720d5df35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Challenge 2: Pizza Runner (Exploratory Data Analysis)]]></title>
            <link>https://medium.com/@emmanuelwale83/sql-challenge-2-pizza-runner-exploratory-data-analysis-5532708e88bf?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/5532708e88bf</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 09:04:22 GMT</pubDate>
            <atom:updated>2024-09-25T20:01:52.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*g1Tu3xtUNNhwVCgX.png" /></figure><h3>Introduction</h3><p>This is the challenge 2 — <a href="https://8weeksqlchallenge.com/case-study-2/">Pizza Runner</a> of the <a href="https://8weeksqlchallenge.com/getting-started/">8 Weeks SQL Challenge</a> by Danny Ma. I am playing the role of a data analyst at Pizza Runner.</p><p>The Week 2 task encompasses both Data Cleaning and Exploratory Data Analysis.</p><p>The Data cleaning phase of the work has been done and well documented in this <a href="https://medium.com/@okonkwoebuka456/sql-challenge-2-pizza-runner-data-wrangling-bf93f15c02f4">article</a>, so make sure you read that before reading this.</p><p>The <strong>Exploratory Data Analysis (EDA)</strong> would be documented in the post. The Full Documentation of this process can be found in my <a href="https://github.com/Ebuka456/Danny-Ma-SQL-Challenge/tree/main/Danny%20Ma%20SQL%20Challenge/Danny&#39;s%20Diner%20Challenge%202">GitHub Repository</a></p><h3>Exploratory Data Analysis</h3><p>To begin this stage, I would like the share the Entity relationship Diagram of the tables in the pizza_runner database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*jlEjlleTo0R6EZVl.jpeg" /></figure><p>For the runners table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*iKaJEvBUzE1SzXdd.jpeg" /></figure><p>The runners table shows the registration_date for each new runner</p><p>For the customer_orders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*BHlKnMVNCA2TgfJ2.jpeg" /></figure><p>Customer pizza orders are captured in the customer_orders table with 1 row for each individual pizza that is part of the order.</p><p>The pizza_id relates to the type of pizza which was ordered whilst the exclusions are the ingredient_id values which should be removed from the pizza and the extras are the ingredient_id values which need to be added to the pizza.</p><p>Note that customers can order multiple pizzas in a single order with varying exclusions and extras values even if the pizza is the same type!</p><p>The exclusions and extras columns will need to be cleaned up before using them in your queries.</p><p>For the runner_orders table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*7z8J8H88Gtqt1ltk.jpeg" /></figure><p>After each orders are received through the system — they are assigned to a runner — however not all orders are fully completed and can be cancelled by the restaurant or the customer.</p><p>The pickup_time is the timestamp at which the runner arrives at the Pizza Runner headquarters to pick up the freshly cooked pizzas. The distance and duration fields are related to how far and long the runner had to travel to deliver the order to the respective customer.</p><p>For the pizza_names table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*-3gDBgjIv4CD1-6E.jpeg" /></figure><p>At the moment — Pizza Runner only has 2 pizzas available the Meat Lovers or Vegetarian!</p><p>For the pizza_recipes table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*VfEPTg7bKL5WNMiA.jpeg" /></figure><p>Each pizza_id has a standard set of toppings which are used as part of the pizza recipe.</p><p>For the pizza_toppings table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/0*bGg5Ra8-sIuIXjxB.jpeg" /></figure><p>This table contains all of the topping_name values with their corresponding topping_id value.</p><h3>Case Study Questions</h3><p>The following Case Study Questions were asked of the database and solutions were provided using SQL</p><ol><li>How many pizzas were ordered?</li></ol><p>Solution:</p><pre>-- How many pizzas were ordered?<br><br>SELECT COUNT(*) AS number_of_ordered_pizzas<br>FROM customer_orders;</pre><p>The question aims to find the number of Pizza ordered by the customers. The COUNT function was use to count the number of rows of the customer_orders table to find out the number of pizza ordered.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/0*I_8KXHiXiNWpw_yf.jpeg" /></figure><p>2. How many unique customer orders were made?</p><pre>SELECT COUNT(DISTINCT order_id) AS distinct_orders_count<br>FROM customer_orders;</pre><p>This problems requires knowledge of counting without including duplicate values. The knowledge can be used to count the unique customer orders</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*66dmzVSE07OZMTxu2O4ikA.png" /></figure><p>3. How many successful orders were delivered by each runner?</p><pre>SELECT runner_id, <br>       COUNT(*) AS number_of_successful_orders<br>FROM runner_orders<br>WHERE cancellation IS NULL<br>GROUP BY runner_id;</pre><p>In this case, successful orders can be described as orders that have null in the cancellation column of the runner_orders table.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/0*Aelg2G38r8O3Pkuh.jpeg" /></figure><p>4. How many of each type of pizza was delivered?</p><pre>SELECT c.pizza_id,<br>    COUNT(*) AS number_of_pizza<br>FROM customer_orders AS c<br>  JOIN runner_orders AS r<br>     USING(order_id)<br>WHERE r.cancellation IS NULL<br>GROUP BY c.pizza_id;</pre><p>This question aims to answer the number of each pizza ordered. This is where the GROUP BY function works best. It groups by the pizza type and then allows for aggregation with another column, in this case, a count function, to count the number of pizza</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*n9W1DD7f-htzNdZo.jpeg" /></figure><p>5. How many Vegetarian and Meatlovers were ordered by each customer?</p><pre>SELECT c.customer_id,<br>    COUNT(CASE WHEN p.pizza_name = &#39;Meatlovers&#39; <br>          THEN pizza_name END) AS count_of_meatlover_pizza_orders,<br>    COUNT(CASE WHEN p.pizza_name = &#39;Vegetarian&#39; <br>          THEN pizza_name END) AS count_of_vegetarian_pizza_orders   <br>FROM customer_orders AS c<br>  JOIN pizza_names AS p<br>     USING(pizza_id)<br>GROUP BY c.customer_id<br>ORDER BY c.customer_id;</pre><p>In this question, the COUNT CASE function is used to answer it. Other methods could be employed but I chose to work with this. The first CASE COUNT statement aims to count the number of “Meatlovers” pizza that were successfully delivered while the second aims to count the “Vegetarian” pizza that were delivered successfully</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*rtb5y3UnWKG9ZqIa.jpeg" /></figure><p>6. What was the maximum number of pizzas delivered in a single order?What was the maximum number of pizzas delivered in a single order?</p><pre>SELECT MAX(Number_of_pizzas) AS maximum_number_of_pizzas<br>FROM(<br> SELECT c.order_id,<br>     COUNT(c.pizza_id) as Number_of_pizzas<br> FROM customer_orders AS c<br>   JOIN runner_orders AS r<br>   USING(order_id)<br> WHERE r.cancellation IS NULL<br> GROUP BY c.order_id<br> ORDER BY Number_of_pizzas DESC<br>    ) AS number_of_orders;</pre><p>For this problem, I used a subquery to first count the number of pizza for each order then the outer query to find the Maximum number of pizza for an order.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/0*s3FgHDOAO1kv1P7T.jpeg" /></figure><p>7. For each customer, how many delivered pizzas had at least 1 change and how many had no changes?</p><pre>SELECT c.customer_id, <br>    COUNT(CASE WHEN exclusions IS NOT NULL OR extras IS NOT NULL THEN 1 END) <br>    AS delivered_pizza_with_least_one_change,<br>    COUNT(CASE WHEN exclusions IS NULL AND extras IS NULL THEN 1 END) <br>    AS delivered_pizza_with_no_change<br>FROM customer_orders AS c<br>   JOIN runner_orders AS r<br>   USING(order_id)<br>WHERE r.cancellation IS NULL<br>GROUP BY c.customer_id<br>ORDER BY c.customer_id;</pre><p>In this question, the changes made are referred to as extras and/orexclusions. Once they included an exclusion or an extras in their order then changes have been made to it. This was the explanation I used to write the codes</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*hr5ic82hXvTJPNyK.jpeg" /></figure><p>8. How many pizzas were delivered that had both exclusions and extras?</p><pre>SELECT COUNT(c.pizza_id) AS pizza_count<br>FROM customer_orders AS c<br>   JOIN runner_orders AS r<br>   USING(order_id)<br>WHERE r.cancellation IS NULL AND c.exclusions IS NOT NULL <br>   AND c.extras IS NOT NULL;</pre><p>This Questions aims to find out the pizza order with both exclusions and extras added to the order. This can be implemented in the WHERE clause</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/65/0*Fey6WvBsbq0CTP31.jpeg" /></figure><p>9. What was the total volume of pizzas ordered for each hour of the day?</p><pre>SELECT HOUR(order_time) AS hour_of_the_day,<br>    COUNT(pizza_id) AS volume_of_pizza<br>FROM customer_orders<br>GROUP BY HOUR(order_time)<br>ORDER BY HOUR(order_time) ASC;</pre><p>The HOUR function extracts the hour of the day from the time stamp using a 24 hours format. The volume in this case represents the number of pizza ordered. Once the hour has been extracted, I then used the GROUP BY function to group by the hour then count the number of pizza ordered in each hour</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*W0c2gwiqYxRA6w8c.jpeg" /></figure><p>10. What was the volume of orders for each day of the week?</p><pre>SELECT DAYOFWEEK(order_time) AS day_of_week,<br>    DAYNAME(order_time) AS day_name,<br>    COUNT(pizza_id) AS volume_of_pizza<br>FROM customer_orders<br>GROUP BY DAYOFWEEK(order_time), DAYNAME(order_time)<br>ORDER BY DAYOFWEEK(order_time) ASC;</pre><p>The DAYOFWEEK function is used to to extract the day of the week from a date function. MySQL counts Sunday as Day 1 which could be confusing, so I used the DAYNAME function to also show the day name as well for easy interpretation</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/0*g7s02q4jCo7B2IiG.jpeg" /></figure><p>Thanks For reading and Feel free to comment, share and correct the codes in case of an error. I would also love feedbacks. The full Data Wrangling process is documented on my <a href="https://github.com/LeoDSaint/danny_pizza_runner">GitHub Repository </a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5532708e88bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Week SQL Challenge Case Study #1 — Danny’s Diner]]></title>
            <link>https://medium.com/@emmanuelwale83/8-week-sql-challenge-case-study-1-dannys-diner-135669f55b36?source=rss-4200b6711968------2</link>
            <guid isPermaLink="false">https://medium.com/p/135669f55b36</guid>
            <dc:creator><![CDATA[ADEWALE ASHOGBON]]></dc:creator>
            <pubDate>Wed, 17 May 2023 05:18:35 GMT</pubDate>
            <atom:updated>2024-02-12T13:38:57.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>8 Week SQL Challenge Case Study #1 — Danny’s Diner</h3><p>Japanese food, sushi, curry, and ramen are the main specialties at the recently launched eatery Danny’s Diner.<br>Danny makes the decision to launch his business in the first few months of 2021 to indulge his passion for Japanese cuisine.</p><p>The restaurant is battling to stay afloat, and Danny understands that in order to make better judgments, he must use the data his company has acquired.<br>This data analysis project’s main goal is to provide answers to various questions regarding customer spending patterns, frequency of visits, and preferred menu items.</p><p>This knowledge will enable Danny to provide his devoted clients with a more personalized experience, ultimately boosting client loyalty and retention.</p><h3>I took on the position of a data analyst in this project to assist Danny in better understanding his customers and making decisions by analyzing the data from his restaurant.</h3><p>To accomplish this, Danny has provided a sample of customer data, which contains three essential datasets: sales, menu, and members. You can check out the datasets <a href="https://8weeksqlchallenge.com/case-study-1/">here</a>.</p><h3>Case Study Questions</h3><p>We are to answer the following case study questions using SQL</p><ol><li>What is the total amount each customer spent at the restaurant?</li><li>How many days has each customer visited the restaurant?</li><li>What was the first item from the menu purchased by each customer?</li><li>What is the most purchased item on the menu, and how many times was it purchased by all customers?</li><li>Which item was the most popular for each customer?</li><li>Which item was purchased first by the customer after they became a member?</li><li>Which item was purchased just before the customer became a member?</li><li>What were the total items and amount spent by each member before they became a member?</li><li>If each $1 spent equates to 10 points and sushi has a 2x point multiplier, how many points would each customer have?</li><li>In the first week after a customer joins the program (including their join date), they earn 2x points on all items, not just sushi. How many points do customers A and B have at the end of January?</li></ol><p>SOLUTION</p><p>For the Case study, I used PostgreSQL<br>1. What<strong> is the total amount each customer spent at the restaurant?</strong></p><p>To generate an answer to the preceding question, I used this line of code.</p><pre>-- 1. What is the total amount each customer spent at the restaurant?<br>SELECT<br>    DISTINCT sales.customer_id,<br>    SUM(menu.price) AS amount_spent<br>FROM<br>    sales<br>    JOIN menu USING (product_id)<br>GROUP BY<br>    1<br>ORDER BY 2 DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*-Uz8_3JYCu04RQSsRqKoww.png" /></figure><p>Answer:</p><p>Customer A spent $76.<br>Customer B spent $74.<br>Customer C spent $36.</p><p>2. <strong>How many days has each customer visited the restaurant?</strong></p><pre>-- 2. How many days has each customer visited the restaurant?<br>SELECT <br>     DISTINCT sales.customer_id,<br>    COUNT( DISTINCT sales.order_date) AS days_visited<br>FROM sales<br>GROUP BY 1<br>ORDER BY 2 DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*lvV00C82CvUcs68UWYuwwQ.png" /></figure><p>Answer:<br>Customer A visited four times.<br>Customer B visited six times.<br>Customer C visited two times.</p><p>3. What<strong> was the first item from the menu purchased by each customer?</strong></p><pre>--3 What was the first item from the menu purchased by each customer?<br>WITH CTE AS (<br>SELECT customer,<br>        product,<br>        RANK() OVER(PARTITION BY customer ORDER BY date ) AS item_rank<br><br>FROM(<br><br>SELECT s.customer_id AS customer,<br>                    s.order_date AS date,<br>                    m.product_name AS product<br><br>        <br>        FROM  sales AS s<br>        LEFT JOIN menu AS m<br>        ON s.product_id = m.product_id) AS subquery)<br><br><br>SELECT customer, product <br>FROM CTE<br>WHERE item_rank = 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*C8sBbkJEF8eGv-vA0Ffq-w.png" /></figure><p>Answer:</p><blockquote>Sushi and curry were Customer A’s first orders.<br>Curry was Customer B’s first order.<br>Ramen was Customer C’s first order.</blockquote><p>4. What<strong> is the most purchased item on the menu, and how many times was it purchased by all customers?</strong></p><pre>-- 4 What is the most purchased item on the menu and how many times was it purchased by all customers?<br><br>SELECT  <br>      m.product_name AS p_id,<br>      COUNT(s.order_date) AS order_time,<br>      RANK() OVER(ORDER BY COUNT(s.order_date) DESC) AS rank<br><br><br>FROM sales AS s<br>LEFT JOIN menu AS m<br>ON s.product_id = m.product_id<br>GROUP BY 1<br>LIMIT 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*mNlkNjW6nCFsrhvt2NxZsw.png" /></figure><p>Answer:</p><blockquote>Ramen was the most frequently purchased item, with 8 purchases.</blockquote><p>5. Which<strong> item was the most popular for each customer?</strong></p><pre>--5. Which item was the most popular for each customer?<br>WITH CTE AS (SELECT<br>                  s.customer_id AS customer ,<br>                  m.product_name AS product_name,<br>                  COUNT(s.order_date) AS order_times,<br>                  RANK() OVER(PARTITION BY s.customer_id ORDER BY COUNT(s.order_date) DESC) AS rank<br>FROM sales AS s<br>LEFT JOIN  menu AS m<br>ON s.product_id = m.product_id<br>GROUP BY  1,2)<br><br>SELECT customer, product_name<br>FROM CTE <br>WHERE rank= 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*eUpNp5eWxYdO_Y80VFYDSw.png" /></figure><p>Answer</p><blockquote>Ramen was Customer ‘A’s’ most popular item, which he or she purchased three times.<br>The most popular items for Customers ‘B’ were Ramen ,Sushi,Curry which the individual bought twice each. Customers ‘C’ bought Ramen three times.</blockquote><p>6. <strong>Which item was purchased first by the customer after they became a member?</strong></p><pre>--6. Which item was purchased first by the customer after they became a member?<br>WITH CTE AS(<br>     SELECT <br>           s.customer_id AS customer , <br>           s.product_id AS p_id,<br>           RANK() OVER(PARTITION BY s.customer_id ORDER BY s.order_date) AS rank<br><br>FROM sales AS s<br>LEFT JOIN members AS m<br>ON s.customer_id = m.customer_id<br><br>WHERE s.order_date &gt; m.join_date)<br><br>SELECT<br>      c.customer AS customer , <br>      m.product_name AS item <br>FROM CTE AS c<br>LEFT JOIN menu AS m<br>ON c.p_id = m.product_id<br>WHERE c.rank = 1<br>ORDER BY 1 ;<br><br><br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*KSF8cOQTsk8zIyljTYigQQ.png" /></figure><blockquote>Answer:</blockquote><p><strong><em>Curry was Customer ‘A’s’ first purchase after signing up for the membership. Customer ‘B’ first purchase after joining was sushi. However, Customer ‘C’ lacks join_date information, which means Customer ‘C’ did not sign up for membership.</em></strong></p><p>7. <strong>Which item was purchased just before the customer became a member?</strong></p><pre>--7 Which item was purchased just before the customer became a member?<br><br><br>WITH CTE AS(SELECT s.customer_id AS customer , s.product_id AS p_id,<br>   RANK() OVER(PARTITION BY s.customer_id ORDER BY s.order_date DESC) AS rank<br><br>FROM sales AS s<br>LEFT JOIN members AS m<br>ON s.customer_id = m.customer_id<br><br>WHERE m.join_date&gt;s.order_date)<br><br>SELECT<br>  c.customer AS customer , m.product_name AS item <br>FROM CTE AS c<br>LEFT JOIN menu AS m<br>ON c.p_id = m.product_id<br>WHERE c.rank = 1<br>ORDER BY 1 ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*7XJ8psUcIcqx43ATKGvECQ.png" /></figure><h3>Answer</h3><blockquote>Customer B purchased curry just before they became a member.</blockquote><blockquote>While,</blockquote><blockquote>Customer A purchased curry&amp;sushi just before they became a member</blockquote><h4>8. What is the total items and amount spent for each member before they became a member?</h4><pre><br>--8 What is the total items and amount spent for each member before they became a member?<br><br>SELECT <br>  s.customer_id, <br>  COUNT( s.product_id) AS items_bought , <br>  SUM(m.price) AS total_amount_spent<br><br>FROM sales AS s<br>LEFT JOIN menu AS m<br>ON s.product_id = m.product_id<br>LEFT JOIN members AS mm<br>ON s.customer_id = mm.customer_id<br>WHERE mm.join_date&gt;s.order_date<br>GROUP BY 1<br>ORDER BY 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*zRntVrDQ7SCdYv-oDrmmhQ.png" /></figure><p>Answer :</p><blockquote>Customer A made 2 purchases worth $25 before signing up for the membership. <br>Customer B, on the other hand, made a total of three purchases for $40.</blockquote><h4>9. If each $1 spent equates to 10 points and sushi has a 2x points multiplier — how many points would each customer have?</h4><pre>--9 If each $1 spent equates to 10 points and sushi has a 2x points multiplier - how many points would each customer have?<br><br>SELECT <br>  s.customer_id AS customer,<br> <br>  SUM(CASE WHEN m.product_name = &#39;curry&#39; OR m.product_name =&#39;ramen&#39; THEN 10* m.price<br>      ELSE 20*m.price END )AS customer_point<br><br><br>FROM sales AS s<br>LEFT JOIN menu AS m<br>ON s.product_id = m.product_id<br>GROUP BY 1<br>ORDER BY 1 ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*9khnfFBq2-N5J2uqXSDGVg.png" /></figure><h3>Answer</h3><p>Customer A has 860 points<br>Customer B has 940 points<br>Customer C has 360 points</p><p><strong>10. In the first week after a customer joins the program (including their join date) they earn 2x points on all items, not just sushi — how many points do customer A and B have at the end of January?</strong></p><p><strong>Assumptions:</strong></p><ul><li>On Day -X to Day 1 (the day a customer becomes a member), each $1 spent earns 10 points. However, for sushi, each $1 spent earns 20 points.</li><li>From Day 1 to Day 7 (the first week of membership), each $1 spent for any item earns 20 points.</li><li>From Day 8 to the last day of January 2021, each $1 spent earns 10 points. However, sushi continues to earn double the points at 20 points per $1 spent.</li></ul><p><strong>Steps:</strong></p><ul><li>Create a CTE called dates_cte.</li><li>In dates_cte, calculate the valid_date by adding 6 days to the join_date and determine the last_date of the month by subtracting 1 day from the last day of January 2021.</li><li>From dannys_diner.sales table, join dates_cte on customer_id column, ensuring that the order_date of the sale is not later than the last_date (sales.order_date &lt;= dates.last_date).</li><li>Then, join dannys_diner.menu table based on the product_id column.</li><li>In the outer query, calculate the points by using a CASE statement to determine the points based on our assumptions above.</li><li>If the product_name is &#39;sushi&#39;, multiply the price by 2 and then by 10. For orders placed between join_date and valid_date, also multiply the price by 2 and then by 10.</li><li>For all other products, multiply the price by 10.</li><li>Calculate the sum of points for each customer.</li></ul><pre><br>WITH dates_cte AS (<br>  SELECT <br>    customer_id, <br>    join_date, <br>    join_date + 6 AS valid_date, <br>    DATE_TRUNC(<br>      &#39;month&#39;, &#39;2021-01-31&#39;::DATE)<br>      + interval &#39;1 month&#39; <br>      - interval &#39;1 day&#39; AS last_date<br>  FROM members<br>)<br><br>SELECT <br>  sales.customer_id, <br>  SUM(CASE<br>    WHEN menu.product_name = &#39;sushi&#39; THEN 2 * 10 * menu.price<br>    WHEN sales.order_date BETWEEN dates.join_date AND dates.valid_date THEN 2 * 10 * menu.price<br>    ELSE 10 * menu.price END) AS points<br>FROM sales<br>JOIN dates_cte AS dates<br>  ON sales.customer_id = dates.customer_id<br>  AND sales.order_date &lt;= dates.last_date<br>JOIN menu<br>  ON sales.product_id = menu.product_id<br>GROUP BY sales.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*jClElTj5YmpfoEcq.png" /></figure><p>Answer:</p><ul><li>Customer A has 1,370 points.</li><li>Customer B has 820 points.</li></ul><h3>Bonus Questions</h3><h3>Join All The Things</h3><p><strong>Recreate the table with: customer_id, order_date, product_name, price, member (Y/N)</strong></p><pre>SELECT <br>  sales.customer_id, <br>  sales.order_date,  <br>  menu.product_name, <br>  menu.price,<br>  CASE<br>    WHEN members.join_date &gt; sales.order_date THEN &#39;N&#39;<br>    WHEN members.join_date &lt;= sales.order_date THEN &#39;Y&#39;<br>    ELSE &#39;N&#39; END AS member_status<br>FROM sales<br>LEFT JOIN members<br>  ON sales.customer_id = members.customer_id<br>JOIN menu<br>  ON sales.product_id = menu.product_id<br>ORDER BY members.customer_id, sales.order_date</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*v3nWCStOxxYNMYTcjxdT0g.png" /></figure><h3>#INSIGHT</h3><h4>From the analysis, we discover the following</h4><p>1. Customer B is the most frequent customer with a 6 visit whereas Customer A spent the highest with a total of $76.<br>2. Ramen is the most popular item on the Menu and it was purchased 8 times followed by sushi.<br>3. Customer A and C’s favorite item is Ramen. Customer B on the other hand loves the 3 items equally.<br>4. Customer A’s first order was Sushi and Curry. Customer B’s first order was Curry while Customer C’s first order was Ramen.<br>5. Sushi and Curry were the items Customer A purchased just before the join date. Whereas Customer B’s was curry.<br>6. Before join date, Customer A purchased 2 items and spent a total amount of $25. Customer B on the other hand purchased 3 items and spent a sum of $40.<br>7. Total points obtained by Customer A, B and C are 860, 940 and 360 respectively.<br>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=135669f55b36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>