<?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 Tetiana Kushniruk on Medium]]></title>
        <description><![CDATA[Stories by Tetiana Kushniruk on Medium]]></description>
        <link>https://medium.com/@tetianakushniruk?source=rss-b7cbbe82f8e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zPQmLbcinn4IuXO7vhda2A.jpeg</url>
            <title>Stories by Tetiana Kushniruk on Medium</title>
            <link>https://medium.com/@tetianakushniruk?source=rss-b7cbbe82f8e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:56:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tetianakushniruk/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[Superstore Sales & Profit Analysis]]></title>
            <link>https://medium.com/@tetianakushniruk/superstore-sales-profit-analysis-4a8a8988aeb1?source=rss-b7cbbe82f8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8a8988aeb1</guid>
            <category><![CDATA[sales-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[profit-margin]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[profitability]]></category>
            <dc:creator><![CDATA[Tetiana Kushniruk]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 17:01:41 GMT</pubDate>
            <atom:updated>2023-07-29T17:01:41.183Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Analysis project with Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LjpzqyZLK_2uI_Bz" /><figcaption>Photo by <a href="https://unsplash.com/@adriendlf?utm_source=medium&amp;utm_medium=referral">Adrien Delforge</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The “Superstore Sales &amp; Profit Analysis” project aims to uncover valuable insights and trends within the <a href="https://www.kaggle.com/datasets/vivek468/superstore-dataset-final">Superstore Dataset</a> obtained from Kaggle. This dataset provides a comprehensive collection of information regarding customer orders, products, sales, and profits, enabling us to delve into the dynamics of a retail environment. By exploring this dataset, we can gain a deeper understanding of the factors influencing store sales and profitability, identify key patterns and trends, and extract actionable insights to enhance business performance.</p><h4>Importing Libraries</h4><pre>import pandas as pd<br>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy import stats<br>import numpy as np<br><br># Setting seaborn color palette<br>palette = sns.set_palette(&#39;Set2&#39;)</pre><h4>Data Exploration and Preprocessing</h4><p>In the data exploration section, we load the dataset and examine its structure, check for missing values, explore unique values in categorical columns to gain a preliminary understanding of the dataset.</p><pre>data = pd.read_csv(&#39;superstore.csv&#39;, encoding=&#39;windows-1252&#39;)<br>data.head()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*qsm39t1HWLFFG0NV3o1u8A.png" /></figure><pre>data.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 9994 entries, 0 to 9993<br>Data columns (total 21 columns):<br> #   Column         Non-Null Count  Dtype  <br>---  ------         --------------  -----  <br> 0   Row ID         9994 non-null   int64  <br> 1   Order ID       9994 non-null   object <br> 2   Order Date     9994 non-null   object <br> 3   Ship Date      9994 non-null   object <br> 4   Ship Mode      9994 non-null   object <br> 5   Customer ID    9994 non-null   object <br> 6   Customer Name  9994 non-null   object <br> 7   Segment        9994 non-null   object <br> 8   Country        9994 non-null   object <br> 9   City           9994 non-null   object <br> 10  State          9994 non-null   object <br> 11  Postal Code    9994 non-null   int64  <br> 12  Region         9994 non-null   object <br> 13  Product ID     9994 non-null   object <br> 14  Category       9994 non-null   object <br> 15  Sub-Category   9994 non-null   object <br> 16  Product Name   9994 non-null   object <br> 17  Sales          9994 non-null   float64<br> 18  Quantity       9994 non-null   int64  <br> 19  Discount       9994 non-null   float64<br> 20  Profit         9994 non-null   float64<br>dtypes: float64(3), int64(3), object(15)<br>memory usage: 1.6+ MB</pre><p>From the provided output, we can extract the following information about the dataset:</p><p><strong>Structure</strong>:</p><ul><li>The dataset has a total of 9994 rows and 21 columns.</li></ul><p><strong>Data Types</strong>:</p><ul><li>The data types of the columns are automatically inferred by Pandas.</li><li>Most of the columns are represented as objects (strings) because they contain categorical or textual information.</li><li>The columns “Row ID,” “Postal Code,” “Quantity,” and “Profit” are represented as integers.</li><li>The columns “Sales,” “Discount,” and “Profit” are represented as floating-point numbers.</li><li><em>The columns “Order Date” and “Ship Date” are currently stored as object types. We’ll deal with that in the next step.</em></li></ul><p><strong>Missing Values</strong>:</p><ul><li>The output does not show any missing values (null values) in any of the columns.</li><li>For all the 9994 rows, each column has a non-null count of 9994, indicating that there are no missing values present in the dataset.</li></ul><h4>Data Types</h4><p>To facilitate time-series analysis, it would be beneficial to convert columns “Order Date” and “Ship Date” to datetime type.</p><pre>data[&#39;Order Date&#39;] = pd.to_datetime(data[&#39;Order Date&#39;])<br>data[&#39;Ship Date&#39;] = pd.to_datetime(data[&#39;Ship Date&#39;])</pre><p>We can also extract additional date-related features like year, month, and day of the week from ‘Order Date’ column for further analysis and visualization.</p><pre>data[&#39;Order Year&#39;] = data[&#39;Order Date&#39;].dt.year<br>data[&#39;Order Month&#39;] = data[&#39;Order Date&#39;].dt.month<br>data[&#39;Order Day of Week&#39;] = data[&#39;Order Date&#39;].dt.dayofweek</pre><p>As we don’t intend to use “Postal Code” for calculations, we can convert it to a object data type.</p><pre>data[&#39;Postal Code&#39;] = data[&#39;Postal Code&#39;].astype(str)</pre><pre>data.dtypes</pre><pre>Row ID                        int64<br>Order ID                     object<br>Order Date           datetime64[ns]<br>Ship Date            datetime64[ns]<br>Ship Mode                    object<br>Customer ID                  object<br>Customer Name                object<br>Segment                      object<br>Country                      object<br>City                         object<br>State                        object<br>Postal Code                  object<br>Region                       object<br>Product ID                   object<br>Category                     object<br>Sub-Category                 object<br>Product Name                 object<br>Sales                       float64<br>Quantity                      int64<br>Discount                    float64<br>Profit                      float64<br>Order Year                    int32<br>Order Month                   int32<br>Order Day of Week             int32<br>dtype: object</pre><h4>Duplicates</h4><p>Let’s check our data for duplicates.</p><pre>data.duplicated().sum()</pre><pre>0</pre><h4>Statistics</h4><p>Let’s look at the summary statistics of the numeric columns.</p><pre>data.describe()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*WbMxztOmRqFwrbi6sRj1Cg.png" /></figure><p>From the provided output, we can observe some insights:</p><ul><li><strong>Extreme Sales Values</strong>: The “Sales” column has a wide range of values (minimum: 0.444, maximum: 22638.48). The maximum value seems unusually high compared to the majority of sales values. It can be potential outliers or transactions that require further investigation.</li><li><strong>Negative Profit</strong>: The minimum value in the “Profit” column is -6599.978, indicating instances where losses were incurred on certain transactions. These negative profit values need further investigation to understand the reasons behind the loss.</li></ul><h4>Outliers</h4><p>Now, based on the previously obtained results, we will check for outliers for the columns “Sales” and “Profit”.</p><p>Through visualizations like box plots, histograms, and scatter plots, we examine the presence of outliers that deviate significantly from the typical distribution of data. We can also use statistical methods such as the z-score or the interquartile range (IQR).</p><pre>fig, axs = plt.subplots(1, 2, figsize=(12, 5))<br>sns.boxplot(x=data[&#39;Sales&#39;], ax=axs[0])<br>sns.boxplot(x=data[&#39;Profit&#39;], ax=axs[1]);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*rL1vTwSDdyKnLrO-BGLVvg.png" /></figure><p>The dots we see outside the whiskers in the boxplots are likely outliers.</p><p>We can additionally use <strong>Z-score</strong> method to identify outliers. By calculating the z-scores for each data point, we can identify which points deviate significantly from the mean and consider them as potential outliers.</p><pre># Select numeric columns<br>data_numeric = data.select_dtypes(include=[np.number])<br><br>for col in data_numeric.columns:<br>    # Calculate z-score of the column<br>    z_score = np.abs(stats.zscore(data[col]))<br>    outliers_num = len(np.where(z_score &gt; 3)[0])<br>    if outliers_num:<br>        print(&#39;{}: {}&#39;.format(col, outliers_num))</pre><pre>Sales: 127<br>Quantity: 113<br>Discount: 300<br>Profit: 107</pre><p>The output shows the number of outliers that have a z-score greater than 3 for the columns “Sales”, “Quantity”, “Discount”, and “Profit”.</p><p>Since the z-score method helps in identifying potential outliers based on their distance from the mean, a z-score greater than 3 is often used as a threshold to detect extreme values.</p><p>There are several ways to deal with outliers in a dataset. One of them is to simply remove these records. We can again use Z-score method to do it.</p><blockquote><strong><em>NOTE:</em></strong> The “Quantity” and “Discount” columns represent discrete variables, therefore it would be better to leave them without changes.</blockquote><pre>data_numeric = data_numeric.drop([&#39;Quantity&#39;, &#39;Discount&#39;], axis=1)<br><br>z_scores = np.abs(stats.zscore(data_numeric))<br><br># Save old DataFrame<br>old_data = data.copy()<br><br># DataFrame without outliers<br>data = data[(z_scores &lt; 3).all(axis=1)]<br>data.shape</pre><pre>(9829, 24)</pre><p>While the summary statistics provide initial insights, visualizations can offer a more comprehensive understanding of the data distribution, relationships between variables, and any anomalies or patterns present in the dataset. Therefore, let’s move on to EDA and data visualization to further explore and analyze the dataset.</p><h4>Exploratory Data Analysis and Data Visualization</h4><h4>Sales and Profit Distribution</h4><p>Now we are going to look at the distribution of numerical columns “Sales” and “Profit” to understand their patterns.</p><pre>fig, ax = plt.subplots(1, 2, figsize=(12, 5))<br>sns.histplot(x=data[&#39;Sales&#39;], ax=ax[0], binwidth=50)<br>sns.histplot(x=data[&#39;Profit&#39;], ax=ax[1], binwidth=50);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*vAruOiZ4z6PH3BC2xYfVjQ.png" /></figure><h4>Sales and Profit over Time</h4><p>Let’s create line plots to observe the trend of sales and profit over different time intervals.</p><p>First we need to aggregate sales and profit monthly for each year.</p><pre>group_by_year_month = data.groupby([&#39;Order Year&#39;, &#39;Order Month&#39;])<br>sales_profit_monthly = group_by_year_month[[&#39;Sales&#39;, &#39;Profit&#39;]].sum().reset_index()</pre><pre>def lineplot_monthly(data, parameter, hue=None, palette=None):<br>    plt.figure(figsize=(10, 6))<br>    sns.lineplot(data=data, x=&#39;Order Month&#39;, y=parameter, hue=hue, marker=&#39;o&#39;, palette=palette)<br>    plt.title(f&#39;Monthly {parameter} Trend&#39;)<br>    plt.xlabel(&#39;Month&#39;)<br>    plt.ylabel(parameter)<br>    plt.xticks(range(1, 13), labels=[&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;, &#39;Jun&#39;, &#39;Jul&#39;, &#39;Aug&#39;, &#39;Sep&#39;, &#39;Oct&#39;, &#39;Nov&#39;, &#39;Dec&#39;])<br>    if hue:<br>        plt.legend(title=&#39;Year&#39;, loc=&#39;best&#39;)<br>    plt.grid(True)</pre><pre>lineplot_monthly(sales_profit_monthly, &#39;Sales&#39;, hue=&#39;Order Year&#39;, palette=&#39;Set2&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*KHJEkd23XXobbVytVnXFHg.png" /></figure><p>Here are the observations we can get from this graph:</p><ul><li>The line plot shows a clear <em>upward trend in sales</em> from January to December each year. It tells us about higher demand during certain months, possibly due to holiday seasons, festive occasions, or annual sales events.</li><li>The sudden <em>drop in sales during October</em> stands out as an anomaly in the otherwise upward trend. Further investigation is required to understand the reasons behind the significant decrease in sales during October. Possible factors could include changes in marketing strategies, external events, or product-related issues during that specific month.</li><li>The yearly sales trend demonstrates an overall positive growth in sales from 2014 to 2017.</li></ul><pre>lineplot_monthly(sales_profit_monthly, &#39;Profit&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*PlLLdFzipIv1sdawG25ZYA.png" /></figure><p>In general there is a similarity in the trend of the profit graph with the sales graph. When sales increase, it leads to a corresponding increase in profit, and vice versa.</p><h4>Segment-wise Sales and Profit</h4><p>In this section we are going to compare sales and profit across different customer segments.</p><pre>sales_profit_by_segment = data.groupby(&#39;Segment&#39;)[[&#39;Sales&#39;, &#39;Profit&#39;]].sum().reset_index()</pre><p>To create a double bar plot with Sales and Profit, we must melt the data into a long format to have a tidy dataset that facilitates the plotting process.</p><pre>sales_profit_by_segment_long = pd.melt(sales_profit_by_segment, id_vars=[&#39;Segment&#39;], <br>                                    var_name=&#39;Measure&#39;, value_vars=[&#39;Sales&#39;, &#39;Profit&#39;], value_name=&#39;Count&#39;)<br>sales_profit_by_segment_long</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*4gg0gEWGPdiTa12M8n1WZQ.png" /></figure><pre>sns.catplot(kind=&#39;bar&#39;, data=sales_profit_by_segment_long, x=&#39;Segment&#39;, y=&#39;Count&#39;, hue=&#39;Measure&#39;, legend_out=False)<br>plt.title(&#39;Sales and Profit by Customer Segment&#39;)<br>plt.xlabel(&#39;Customer Segment&#39;)<br>plt.legend(loc=&#39;best&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*ihVdPO6DJ_3fz-yeUjp-Kg.png" /></figure><p>At first sight the “Consumer” segment has the highest sales and the highest profit. But can we claim that it is the most profitable segment?</p><p>The answer is No. We should look at <strong>Profit Margin</strong>. It looks like the “Home Office” has the highest one. Let’s check it.</p><pre>sales_profit_by_segment[&#39;Profit/Sales&#39;] = sales_profit_by_segment[&#39;Profit&#39;]/sales_profit_by_segment[&#39;Sales&#39;]<br>sales_profit_by_segment</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*oKB4tNTdCMlJtzaBWG_myA.png" /></figure><p>Now we can see that the “Home Office” segment has the highest Profit/Sales ratio, making it the most efficient in terms of profitability.</p><p>The “Consumer” segment has the lowest Profit/Sales ratio, suggesting that it retains a slightly lower proportion of its sales revenue as profit compared to the other segments.</p><p>Overall, the Profit Margins for all three segments are relatively close, indicating that the company is generally managing profitability efficiently across its different customer segments.</p><h4>Sales and Profit by Category and Sub-Category</h4><p>After analyzing Sales and Profit by customer segment, let’s identify the top-performing and underperforming categories and sub-categories.</p><pre>sales_profit_by_category = data.groupby([&#39;Category&#39;])[[&#39;Sales&#39;, &#39;Profit&#39;]].sum().reset_index()</pre><pre>fig, ax = plt.subplots(1, 2, figsize=(10, 6))<br>ax[0].pie(sales_profit_by_category[&#39;Sales&#39;], labels=sales_profit_by_category[&#39;Category&#39;], autopct=&#39;%1.1f%%&#39;)<br>ax[0].title.set_text(&#39;Sales by Category&#39;)<br>ax[1].pie(sales_profit_by_category[&#39;Profit&#39;], labels=sales_profit_by_category[&#39;Category&#39;], autopct=&#39;%1.1f%%&#39;)<br>ax[1].title.set_text(&#39;Profit by Category&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Qhwcu2zcwed5tJ8PtOVY2g.png" /></figure><p>It’s obvious that “Furniture”, “Office Supplies”, and “Technology” have relatively similar sales percentages, with each contributing to approximately 1/3 of total sales.</p><p>“Office Supplies” generate the highest profit, accounting for 50.2% of total profits, despite having a similar sales percentage to Furniture and Technology. “Furniture”, while having almost similar sales percentage (even the highest), contributes to only 8.3% of total profits, indicating lower profit margins compared to the other categories.</p><pre>sales_profit_by_subcategory = data.groupby([&#39;Sub-Category&#39;])[[&#39;Sales&#39;, &#39;Profit&#39;]].sum().reset_index()<br><br>sales_profit_by_subcategory_long = pd.melt(sales_profit_by_subcategory, id_vars=[&#39;Sub-Category&#39;], <br>                                    var_name=&#39;Measure&#39;, value_vars=[&#39;Sales&#39;, &#39;Profit&#39;], value_name=&#39;Count&#39;)</pre><pre>sns.catplot(kind=&#39;bar&#39;, data=sales_profit_by_subcategory_long, x=&#39;Sub-Category&#39;, y=&#39;Count&#39;, hue=&#39;Measure&#39;, legend_out=False, <br>           height=4.5, aspect=2)<br>plt.title(&#39;Sales and Profit by Sub-Category&#39;)<br>plt.legend(loc=&#39;best&#39;);<br>plt.xticks(rotation=45);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*5xtHqXpiercL5U4JIzFgbQ.png" /></figure><p>We can see that some sub-categories (e.g., “Accessories” or “Appliances”) have high sales and substantial profits, making them highly profitable for the business.</p><p>On the other hand, there are sub-categories (e.g., “Bookcases” or “Tables”) which are incurring losses, indicating the need for further investigation into their cost structures and pricing strategies to improve profitability.</p><p>For a better understanding, we can take a closer look at the <strong>Profit Margin</strong>. And let’s additionally divide sub-categories into 3 groups: highly profitable, moderately profitable, and unprofitable.</p><pre>sales_profit_by_subcategory[&#39;Profit/Sales&#39;] = sales_profit_by_subcategory[&#39;Profit&#39;]/sales_profit_by_subcategory[&#39;Sales&#39;]<br><br>sales_profit_by_subcategory[&#39;Profitability&#39;] = pd.cut(sales_profit_by_subcategory[&#39;Profit/Sales&#39;], <br>                                                     bins=[-np.inf, 0, 0.2, np.inf],<br>                                                     labels=[&#39;loss&#39;, &#39;moderate&#39;, &#39;high&#39;])<br>sales_profit_by_subcategory</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*ObFrgcJxHRxM8s4SBql6yg.png" /></figure><p>Now we can clearly see which subcategory is the most profitable and which is the unprofitable one.</p><h4>Sales and Profit by City and Region</h4><p>In this section, I’d like to analyze Sales and Profit in different locations.</p><pre>sales_profit_by_region_city = data.groupby([&#39;Region&#39;, &#39;City&#39;])[[&#39;Sales&#39;, &#39;Profit&#39;]].sum().reset_index()</pre><p>Since we have many cities, let’s analyze only the top 15.</p><pre>def top(data, parameter, top=15):<br>    data = data.sort_values(by=[parameter], ascending=False)[:top]<br>    plt.figure(figsize=(10, 6))<br>    sns.barplot(data=data, x=parameter, y=&#39;City&#39;, hue=&#39;Region&#39;)<br>    plt.title(f&#39;Top {top} Cities by {parameter}&#39;)<br>    plt.legend(loc=&#39;best&#39;)<br>    return data</pre><pre>top(sales_profit_by_region_city, &#39;Sales&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*1PZhX10Ky6d_5qNCMwryLA.png" /></figure><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*GcwGc0uUSoDwMUFshc2GUw.png" /></figure><pre>top(sales_profit_by_region_city, &#39;Profit&#39;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*RxwpO4g_QeTo9_DmSvDNdQ.png" /></figure><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*S1dvlQmzMj0tZ6hjotRHRg.png" /></figure><p>Insights from the provided outputs:</p><ol><li><strong>Top Sales</strong> by Region and City:</li></ol><ul><li>The cities with the highest sales are <em>New York City</em> (Region: East), followed by <em>Los Angeles</em> (Region: West), and <em>San Francisco</em> (Region: West).</li></ul><p>2.<strong> Top Profit</strong> by Region and City:</p><ul><li>The cities with the highest profits are <em>New York City</em> (Region: East), followed by <em>Los Angeles</em> (Region: West), and <em>Seattle</em> (Region: West).</li><li>Notice, that Seattle, despite having lower sales compared to San Francisco, surpasses it in terms of profit.</li></ul><p>3. <strong>Negative Profit</strong> Cities:</p><ul><li>Some cities, such as Philadelphia (Region: East), Chicago (Region: Central), Jacksonville (Region: South), Dallas (Region: Central), Columbus (Region: East), and Denver (Region: West), have negative profits, indicating losses.</li></ul><h4>Summary</h4><p>In this data analysis project, we explored a dataset from a superstore, examining various aspects related to store sales and profitability. We performed Exploratory Data Analysis (EDA) to gain insights into the data distribution, including visualizations of sales and profit across different categories and sub-categories. Additionally, we analyzed sales and profit metrics by customer segments, regions, and cities. Outliers were detected and handled using z-scores to ensure data integrity.</p><p>Throughout the project, important insights are derived to make data-driven decisions:</p><ul><li>Upward trend in sales and profit from January to December with drop during October.</li><li>The three categories, Office Supplies, Furniture, and Technology, have almost equal shares in total sales, but their profitability varies significantly. Office Supplies contribute the most to profitability, while Furniture has the lowest one.</li><li>The analysis highlights the profitability of different sub-categories, which were divided into highly profitable, moderately profitable, and unprofitable.</li><li>The “Home Office” segment stands out as the most profitable, followed by “Corporate” and “Consumer” segments.</li><li>New York City and Los Angeles dominate both in terms of sales and profit. Seattle demonstrates higher profitability than San Francisco despite lower sales.</li></ul><p>Overall, the “Superstore Sales &amp; Profit Analysis” project provides valuable insights into the store’s performance and profitability. These insights can guide strategic decision-making, resource allocation, and marketing efforts to optimize sales and increase profitability for the superstore. The project showcases the power of data analysis in understanding business trends and driving informed actions to enhance overall success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8a8988aeb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Lifetime Analysis: Data Analysis project with Python]]></title>
            <link>https://medium.com/@tetianakushniruk/customer-lifetime-analysis-data-analysis-project-with-python-c9417e724094?source=rss-b7cbbe82f8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9417e724094</guid>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[customer-lifetime-value]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Tetiana Kushniruk]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 17:57:44 GMT</pubDate>
            <atom:updated>2023-06-20T05:40:14.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>Customer Lifetime Value Analysis: Data Analysis project with Python</h3><h4>Exploring Customer Acquisition Channels, ROI, and CLTV for Informed Decision-Making</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ho2GKwNqS1NDpEaX" /><figcaption>Photo by <a href="https://unsplash.com/@headwayio?utm_source=medium&amp;utm_medium=referral">Headway</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s competitive business landscape, understanding customers’ behavior and optimizing customer acquisition strategies are crucial for sustainable growth. This data analysis project aims to uncover valuable insights that can inform decision-making and improve business strategies.</p><h4>Table of Contents</h4><ul><li><a href="#76fb">Importing Libraries</a></li><li><a href="#ee8e">Exploratory Data Analysis and Data Visualization</a><br>- <a href="#9ead">Overview of the Dataset</a><br>- <a href="#8213">Distribution of Numeric Variables</a><br>- <a href="#d5f8">Distribution of Categorical Variables</a><br>- <a href="#37e2">Grouping and Aggregating Data</a></li><li><a href="#257a">Return on Investment (ROI)</a><br>- <a href="#93fb">ROI by Channel Analysis</a><br>- <a href="#4602">ROI and Other Variables Analysis</a></li><li><a href="#13df">Customer Lifetime Value (CLTV)</a><br>- <a href="#2256">CLTV by Channel</a></li><li><a href="#6996">Summary</a></li></ul><h4>Importing Libraries</h4><pre>import pandas as pd<br>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Setting seaborn color palette<br>palette = sns.set_palette(&#39;Set2&#39;)</pre><h4>Exploratory Data Analysis and Data Visualization</h4><h4>Overview of the <a href="https://statso.io/customer-lifetime-value-analytics-case-study/">Dataset</a></h4><p>In this step, we will start by summarizing the dataset, including its size, column names, and any missing values. We will calculate basic statistics to gain an understanding of the dataset’s overall characteristics.</p><pre>data = pd.read_csv(&#39;customer_acquisition_data.csv&#39;)<br>data.head()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*S3jioYpnI8WD1oc9WpehcQ.png" /></figure><pre>data.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 800 entries, 0 to 799<br>Data columns (total 5 columns):<br> #   Column           Non-Null Count  Dtype  <br>---  ------           --------------  -----  <br> 0   customer_id      800 non-null    int64  <br> 1   channel          800 non-null    object <br> 2   cost             800 non-null    float64<br> 3   conversion_rate  800 non-null    float64<br> 4   revenue          800 non-null    int64  <br>dtypes: float64(2), int64(2), object(1)<br>memory usage: 31.4+ KB</pre><p>From this information, we can gather the following:</p><ul><li>The dataset does not contain any missing values (all columns have 800 non-null values).</li><li>The ‘customer_id’ column is a unique identifier for each customer and is stored as integers.</li><li>The ‘channel’ column represents the acquisition channel through which customers were acquired, and it contains categorical data.</li><li>The ‘cost’ column represents the acquisition cost for each customer, and it is stored as floating-point numbers.</li><li>The ‘conversion_rate’ column represents the conversion rate for each customer, also stored as floating-point numbers.</li><li>The ‘revenue’ column represents the revenue generated by each customer and is stored as integers.</li></ul><pre>data.describe()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*iWR0E_-8F8DqXULfZk0jeA.png" /></figure><p>After reading and loading the dataset, we computed basic statistics for the numeric columns: ‘cost’, ‘conversion_rate’, and ‘revenue’. These basic statistics give us a preliminary understanding of the dataset’s characteristics and serve as a starting point for further exploration and analysis.</p><h4>Distribution of Numeric Variables</h4><p>We will examine the distributions of numeric variables, such as ‘cost’, and ‘revenue’. By visualizing these distributions, we can determine their shapes, ranges, and identify any outliers.</p><pre>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))<br>ax1.set_title(&#39;Distribution of Cost&#39;)<br>sns.histplot(data, x=&#39;cost&#39;, kde=True, ax=ax1)<br>ax2.set_title(&#39;Distribution of Revenue&#39;)<br>sns.histplot(data, x=&#39;revenue&#39;, kde=True, ax=ax2);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*T7kKMvUUnVAuieSZrh_TBQ.png" /></figure><p>We can see that the ‘cost’ variable contains 4 unique values and has a relatively balanced distribution around an average value of 200, with moderate variability.</p><p>As for the ‘revenue’ variable, it has been categorized into 11 bins. From it’s histogram, we can conclude that this variable has a relatively narrow range and moderate variability (most observations clustered around the mean).</p><h4>Distribution of Categorical Variables</h4><p>To understand the distribution of the categorical variable ‘channel’, we will create a visual representation, such as bar chart. This will allow us to observe the proportions of customers acquired through different channels, identify the most common and least common channels, and assess the balance of the data.</p><pre>sns.countplot(data, x=&#39;channel&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*EuMp13OZgAx8X8WB8Dd0vw.png" /></figure><p>The counts for each channel appear to be relatively close to each other. This suggests that the customer acquisition efforts were distributed somewhat evenly across these channels.</p><h4>Grouping and Aggregating Data</h4><p>Aggregating the data allows us to calculate summary statistics and gain insights into the average performance of different groups.</p><p>We can aggregate the data by the acquisition channel to analyze the performance of each channel. For example, we can calculate the average ‘cost’, ‘conversion_rate’, and ‘revenue’ for each channel to understand which channels are most effective.</p><pre># Grouping the data based on &#39;channel&#39;<br>channel_groups = data.groupby(&#39;channel&#39;)<br># Aggregating &#39;cost&#39; for each channel group<br>cost_by_channel = channel_groups[&#39;cost&#39;].mean().reset_index()<br><br>sns.barplot(cost_by_channel, x=&#39;channel&#39;, y=&#39;cost&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*byRvH_KwBJ01QoVOQggZQQ.png" /></figure><p>From this analysis, we can observe that paid advertising has the highest average cost. On the other hand, social media, email marketing and referrals have relatively lower average costs.</p><pre># Aggregating &#39;conversion_rate&#39; for each channel group<br>conversion_rate_by_channel = channel_groups[&#39;conversion_rate&#39;].mean().reset_index()<br><br>sns.barplot(conversion_rate_by_channel, x=&#39;channel&#39;, y=&#39;conversion_rate&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*cq_V_ytjnzk_cV2RV5sYVQ.png" /></figure><p>Social media has the highest average conversion rate, indicating that it may be a more successful channel for acquiring customers who convert into revenue. Referral also has relatively high conversion rate. Paid advertising and email marketing have the lowest average conversion rates, implying that they may require further optimization or targeting strategies to improve conversion rates.</p><pre># Aggregating &#39;revenue&#39; for each channel group<br>revenue_by_channel = channel_groups[&#39;revenue&#39;].sum().reset_index()<br><br>fig, ax = plt.subplots(figsize=(8, 6))<br>plt.pie(revenue_by_channel[&#39;revenue&#39;], labels=revenue_by_channel[&#39;channel&#39;], autopct=&#39;%1.1f%%&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*FPzraikxWe-tFKmOMQsSTw.png" /></figure><p>The aggregation result suggests that each channel plays a significant role in generating revenue, with email marketing being the highest contributor. It implies that allocating resources and focusing efforts on these channels may be beneficial for maximizing revenue generation.</p><h4>Return on Investment (ROI)</h4><p>Return on Investment (ROI) is a financial metric used to evaluate the profitability and efficiency of an investment. It measures the return or gain generated from an investment relative to its cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*3dcV48Knu1sro_VFPxM-5w.png" /></figure><pre>data[&#39;roi&#39;] = (data[&#39;revenue&#39;] - data[&#39;cost&#39;]) / data[&#39;cost&#39;]<br>data.head()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*C_Nhj_qhBA-SrssEwbTv9Q.png" /></figure><h4>ROI by Channel Analysis</h4><p>Now let’s perform ROI by Channel Analysis which will allow us to assess the profitability of investments made through different acquisition channels.</p><pre>roi_by_channel = data.groupby(&#39;channel&#39;)[&#39;roi&#39;].mean().reset_index()<br><br>sns.barplot(roi_by_channel, x=&#39;channel&#39;, y=&#39;roi&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*kqUQuD8vzU4O-U77B-jSfQ.png" /></figure><p>Based on the analysis, email marketing appears to be the most effective channel in terms of generating returns, followed by referral and social media. Paid advertising, on the other hand, seems to have a lower ROI compared to the other channels.</p><h4>ROI and Other Variables Analysis</h4><p>Performing ROI and other variables analysis can provide valuable insights into the relationship between profitability and various factors such as conversion rates, costs, and revenue.</p><pre># Computing the correlation matrix<br>corr = data[[&#39;roi&#39;, &#39;cost&#39;, &#39;conversion_rate&#39;, &#39;revenue&#39;]].corr()<br><br>sns.heatmap(corr, annot=True, cmap=sns.color_palette(&#39;Purples_d&#39;));</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*djLB0P1l1wz_HcnOd3PiKw.png" /></figure><p>The correlation matrix suggests that cost and revenue have the strongest relationships with ROI. Higher costs are associated with lower ROI, while higher revenue is associated with higher ROI. The conversion rate alone does not show a significant correlation with ROI.</p><h4>Customer Lifetime Value (CLTV)</h4><p>CLTV (Customer Lifetime Value) analysis is a method used by businesses to estimate the total value a customer will generate over the entire duration of their relationship with the company. It is a valuable metric that helps businesses understand the long-term profitability and worth of their customer base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*mPmWsS2t3jGYodCVtKhLaQ.png" /></figure><pre>data[&#39;cltv&#39;] = (data[&#39;revenue&#39;] - data[&#39;cost&#39;]) * data[&#39;conversion_rate&#39;] / data[&#39;cost&#39;]<br>data.head()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*sEO3rKvTeCudiSoa3DizDw.png" /></figure><h4>CLTV by Channel</h4><p>Calculating CLTV by channel allows us to assess the long-term value of customers acquired through different marketing channels.</p><pre>cltv_by_channel = data.groupby(&#39;channel&#39;)[&#39;cltv&#39;].mean().reset_index()<br><br>sns.barplot(cltv_by_channel, x=&#39;channel&#39;, y=&#39;cltv&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*gUnPX__SkaZlwSqfur3ANQ.png" /></figure><p>Based on the analysis, referral and social media channels stand out as the most effective in terms of generating higher customer lifetime value (CLTV). Email marketing also performs reasonably well, while paid advertising lags behind in terms of CLTV.</p><p>Now let’s compare the CLTV of the referral and social media channels to get additional insights.</p><pre># Selecting records where channel is referral or social media<br>select = data[data[&#39;channel&#39;].isin([&#39;referral&#39;, &#39;social media&#39;])]<br><br>sns.catplot(select, x=&#39;channel&#39;, y=&#39;cltv&#39;, kind=&#39;box&#39;);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*iKlwh_qZ2CII3N8kziuYHg.png" /></figure><p>We can see that the social media channel performs the best, but the referral channel is not much worse.</p><h4>Summary</h4><p>In this data analysis project, we explored the concept of Customer Lifetime Value (CLTV) and its relationship to various marketing channels.</p><p>EDA was performed to gain insights into the distribution and characteristics of the data. Various visualizations, such as histograms, bar charts, pie and box plots, heatmap were used to analyze the distribution of variables, identify patterns, and understand relationships between variables.</p><p>Aggregations, such as calculating the average cost and conversion rate, total revenue for each channel, provided an overview of how different channels contribute to overall results.</p><p>The Return on Investment (ROI) analysis helped assess the profitability and effectiveness of each channel in generating revenue.</p><p>We estimated the Customer Lifetime Value (CLTV) for each channel to understand the long-term value generated by customers acquired through different channels.</p><p>The analysis provided valuable insights which can guide resource allocation, marketing strategies, and channel optimization efforts to maximize long-term customer value and business success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9417e724094" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Data Cleaning in Python]]></title>
            <link>https://medium.com/@tetianakushniruk/a-beginners-guide-to-data-cleaning-in-python-fb5f15ff00d8?source=rss-b7cbbe82f8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb5f15ff00d8</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Tetiana Kushniruk]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 18:20:58 GMT</pubDate>
            <atom:updated>2023-04-07T18:26:41.924Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cleaning and Preparing the NYC Airbnb Dataset for Data Analysis step-by-step</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TPjnQOX9bDFkm-Ns" /><figcaption>Photo by <a href="https://unsplash.com/@onevagabond?utm_source=medium&amp;utm_medium=referral">Paulo Silva</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data cleaning is a crucial step in the process of data analysis. It involves identifying and correcting errors, inconsistencies, and missing values in a dataset. This process is essential as it ensures the accuracy and completeness of the data before conducting any analysis.</p><p>In this article, we will focus on the <a href="https://www.kaggle.com/datasets/dgomonov/new-york-city-airbnb-open-data">NYC Airbnb dataset</a> and explore the different techniques and tools used in data cleaning. We will cover topics such as handling missing data, dealing with outliers, and preparing the dataset for analysis.</p><h3>Import Libraries</h3><pre>import pandas as pd<br>import numpy as np<br>from scipy import stats<br><br>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><h3>Read CSV file and Understand the data</h3><p>Before you start cleaning your data, it’s important to understand what your data represents, what the values mean, and what kind of problems might arise during cleaning. This understanding can help you choose the right cleaning techniques and avoid errors.</p><pre># Create a DataFrame from CSV file<br>df = pd.read_csv(&#39;/kaggle/input/new-york-city-airbnb-open-data/AB_NYC_2019.csv&#39;)<br><br># First 5 rows of the DataFrame<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*d85X1iKbKBOdBRCXtwlMvg.png" /><figcaption>First part of the table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*eXZ4-NvAbpwTcFs-t66rmQ.png" /><figcaption>Second part of the table</figcaption></figure><pre># The summary information about the DataFrame<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*xLZwsAUITKBk3F-1L7Pi7w.png" /><figcaption>Output: summary information about the DataFrame</figcaption></figure><p>From this output, we can see that the DataFrame has 48,895 rows (entries) and 16 columns. The columns have different data types, including int64, float64, and object. We can also see that some columns have missing values (‘name’, ‘host_name’, ‘last_review’, and ‘reviews_per_month’), as indicated by the difference between the total number of entries (48,895) and the number of non-null values for those columns.</p><h3>Data Types</h3><p>We can see that ‘last_review’ column contains dates, but it’s type is object. There is a need to change it to a datetime data type. It’ll allow to perform calculations on the dates.</p><pre>df[&#39;last_review&#39;] = pd.to_datetime(df[&#39;last_review&#39;])</pre><p>Columns ‘neighbourhood_group’, ‘neighbourhood’, and ‘room_type’ are categorical variables, so it’ll be more appropriate to convert them from an object to a category type.</p><pre>df[&#39;neighbourhood_group&#39;] = df[&#39;neighbourhood_group&#39;].astype(&#39;category&#39;)<br>df[&#39;neighbourhood&#39;] = df[&#39;neighbourhood&#39;].astype(&#39;category&#39;)<br>df[&#39;room_type&#39;] = df[&#39;room_type&#39;].astype(&#39;category&#39;)</pre><p>Now we can see unique categories in these columns:</p><pre>df[&#39;neighbourhood_group&#39;].values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YCZLFENR24_tozwSOrAHg.png" /><figcaption>Output: values of categorical variable ‘neighbourhood_group’</figcaption></figure><pre># Check the data types<br>df.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*PC7Sv3H0jDxyowpzdfjxqw.png" /><figcaption>Output: data types of each column</figcaption></figure><h3>Duplicates</h3><p>Duplicate rows can cause problems in your analysis by inflating the weight of some observations, skewing the results of statistical analyses, or even giving an incorrect impression of the underlying data.</p><pre>df.duplicated().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*PyoWqy0pQpdI_MEFagpkiQ.png" /><figcaption>Output: number of duplicate raws in the DataFrame</figcaption></figure><p>There are no duplicate rows in the DataFrame.</p><h3>Missing Data</h3><p>Missing data can cause problems in your analysis, such as biased results, incorrect statistical inferences, and errors in machine learning models. By identifying missing data, you can decide how to handle it, whether it’s by imputing the missing values or dropping the rows with missing values.</p><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*exhA6V8TfWkoLPUzlelysQ.png" /><figcaption>Output: number of null values in each column</figcaption></figure><p>There are missing values in four columns: ‘name’, ‘host_name’, ‘last_review’, and ‘reviews_per_month’.</p><p>Techniques to deal with missing data:</p><ul><li><em>Deletion</em>: You can simply delete the missing values or the entire row or column where they occur. However, this should only be done if the amount of missing data is small and there is no important information in the missing values.</li><li><em>Imputation</em>: You can impute (fill in) the missing values with some other value or technique. This can be done by replacing missing values with a mean, median, or mode of the data, or by using more sophisticated techniques like regression or machine learning algorithms to predict the missing values.</li><li><em>Interpolation</em>: You can use interpolation techniques to estimate the missing values by using the values of neighboring data points. This is particularly useful for time series data.</li><li><em>Data augmentation</em>: You can use data augmentation techniques to create new data points based on existing data points. This can be done by using statistical techniques to generate new values or by using machine learning algorithms to generate new data points.</li></ul><p>Considering the fact that ‘name’ column is insignificant for future data analysis, so we can simply replce null values with ‘N/A’.</p><pre>df.fillna({&#39;name&#39;: &#39;N/A&#39;}, inplace=True)</pre><p>The ‘host_name’ column is irrelevant and there is no need to store people names. This column can be dropped.</p><p>The ‘last_review’ column contains the date of the last review and missing values simply mean that there no reviews for this item. This column is also irrelevant for future data analysis and we can also drop it.</p><pre>df.drop([&#39;id&#39;, &#39;host_name&#39;, &#39;last_review&#39;], axis=1, inplace=True)</pre><p><strong><em>NOTE:</em></strong> The ‘id’ column is often dropped from a dataset during the data cleaning process, because it doesn’t provide any meaningful insights for the analysis.</p><p>The ‘reviews_per_month’ column gives information about the number of reviews per month. Since a missing value means the item has no reviews for all time, it has 0 reviews per month.</p><pre>df.fillna({&#39;reviews_per_month&#39;: 0}, inplace=True)</pre><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*urMvCJnqNUl-4W_whx2uVg.png" /><figcaption>Output: number of null values in each column</figcaption></figure><p>Now you can see that we solved the problem of missing values.</p><h3>Outliers</h3><p><em>Outliers</em> are data points that are significantly different from other data points in a dataset. They can be much larger or much smaller than the other data points in the dataset and can distort the overall analysis of the data.</p><p>There are different techniques to identify outliers, such as using boxplots, scatterplots, or mathematical methods such as the z-score or the interquartile range (IQR). Once outliers are identified, they can be dealt with by either removing them from the dataset, adjusting them to more reasonable values, or treating them as a separate category in the analysis.</p><pre># Statistics of the numerical columns in the DataFrame<br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*k7c1BRQ5dipjjkBEdzZP5g.png" /><figcaption>First part of the output table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*xc2Q1Y_ifVtl0njQjCbXpA.png" /><figcaption>Second part of the output table</figcaption></figure><p>Here are some observations from the output:</p><ul><li>‘price’: The minimum price is 0, which seems strange, and the maximum price is 10,000, which is significantly higher than the 75th percentile. It also has high standard deviation.</li><li>‘minimum_nights’: The maximum value is 1,250, which is much higher than the 75th percentile.</li><li>‘number_of_reviews’: The maximum value is 629, which is much higher than the 75th percentile.</li><li>‘reviews_per_month’: The maximum value is 58.5, which is much higher than the 75th percentile.</li><li>‘calculated_host_listings_count’: The maximum value is 327, which is much higher than the 75th percentile.</li></ul><p>All these factors indicate that there may be outliers in these columns.</p><p>It is important to investigate these columns further to determine if there are indeed outliers and how they should be handled in the data analysis process.</p><pre>outlier_cols = [<br>    &#39;price&#39;, &#39;minimum_nights&#39;, &#39;number_of_reviews&#39;, <br>    &#39;reviews_per_month&#39;, &#39;calculated_host_listings_count&#39;<br>]</pre><pre>for col in outlier_cols:<br>    plt.figure(figsize=(5, 5))<br>    sns.boxplot(x=df[col])<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*pwPbqMi1f7c0Nab5SOngLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*VaqHsVWru7x-DcFYlp0lsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*e6Yp1LevCGAzYikrAsBPXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*g1J2Q6sn_rOUlnGvHA6TEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*uDghHr8WRCOZMUylqy1zXA.png" /></figure><p>Now we see that there are indeed outliers in all of these columns.</p><h4>Z-score</h4><p>We can also try a Z-score method to discover outliers. This method uses the standard deviation of the data to calculate the number of standard deviations a data point is away from the mean. A data point that falls outside a certain range (typically, outside 3 standard deviations from the mean) is considered an outlier.</p><p>Let’s find outliers in all numerical columns.</p><pre># Select numeric columns<br>df_numeric = df.select_dtypes(include=[np.number])<br><br>for col in df_numeric.columns:<br>    # Calculate z-score of the column<br>    z_score = np.abs(stats.zscore(df[col]))<br>    outliers_num = len(np.where(z_score &gt; 3)[0])<br>    if outliers_num:<br>        print(&#39;{}: {}&#39;.format(col, outliers_num))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*Ih1qvnFP6cn8rLj9nJoWiA.png" /><figcaption>Output: number of outliers in numeric columns</figcaption></figure><p>This method helped us to find outliers that we didn’t see when analyzing the describe table.</p><pre>sns.boxplot(x=df[&#39;latitude&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*wjyO6cfyIdZY4E17QZOrwg.png" /></figure><pre>sns.boxplot(x=df[&#39;longitude&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*iHd4QHpStQProWuH1gyhzg.png" /></figure><h4>Dealing with Outliers</h4><p>There are several ways to deal with outliers in a dataset:</p><ul><li>Remove the outliers: You can simply remove the rows containing outliers from your dataset. However, this can also lead to loss of information and affect the accuracy of your model. So, you should be careful while removing the outliers and make sure you have a valid reason for doing so.</li><li>Replace the outliers: You can replace the outliers with a value that makes more sense, for example, the mean, median, or mode of the data. This method can help preserve the data and still reduce the effect of outliers.</li><li>Transform the data: You can transform the data using techniques like log transformation, box-cox transformation, etc. This can help in reducing the effect of outliers and also improve the distribution of the data.</li></ul><p>We can use Z-score method to remove outliers.</p><pre>z_scores = np.abs(stats.zscore(df_numeric))<br><br># DataFrame without outliers<br>df_wo_outliers = df[(z_scores &lt; 3).all(axis=1)]<br>df_wo_outliers.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*2gENoDXefja3kv8BFopvKQ.png" /><figcaption>Output (shape of the DataFrame without outliers)</figcaption></figure><h3>Done!</h3><p>We have covered the basics of data cleaning, including how to check for and handle duplicates, how to deal with missing data, and how to identify and handle outliers.</p><p>Thank you for reading the article! I hope you found it informative and helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb5f15ff00d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping Booking.com with Beautiful Soup for Hotel Data Analysis]]></title>
            <link>https://medium.com/@tetianakushniruk/web-scraping-booking-com-with-beautiful-soup-for-hotel-data-analysis-95f874820c18?source=rss-b7cbbe82f8e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f874820c18</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <dc:creator><![CDATA[Tetiana Kushniruk]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 12:44:08 GMT</pubDate>
            <atom:updated>2023-04-06T12:52:28.108Z</atom:updated>
            <content:encoded><![CDATA[<h4>From HTML to CSV: Mastering Web Scraping with Beautiful Soup</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q8Rab5cygSNatahu" /><figcaption>Park Plaza Westminster Bridge London photo from <a href="https://www.booking.com/hotel/gb/park-plaza-westminster-bridge.en-gb.html?aid=356980&amp;label=gog235jc-1DCAMoUDi1AkgJWANo6QGIAQGYAQm4ARfIAQzYAQPoAQH4AQKIAgGoAgO4Avz4uqEGwAIB0gIkNGRkODNkMjktYmY4MC00NWVmLWE3NzItOWMxZmMyMGVlYmFm2AIE4AIB&amp;sid=d92145f0c644ea939e019427092e2903&amp;activeTab=photosGallery">Booking.com</a></figcaption></figure><p>Booking.com is one of the most popular online travel agencies in the world, providing travelers with access to millions of hotel and accommodation options across the globe.</p><p><strong>Project Objective</strong>: The objective of this project is to collect data from Booking.com using web scraping techniques. The main goal is to extract data related to hotels, including prices, ratings, reviews, amenities, and locations. This data can be used in future to identify patterns and trends in customer behavior, such as popular destinations, preferred amenities, and booking patterns.</p><h3>Importing Libraries</h3><ul><li><em>BeautifulSoup (bs4)</em> is used to extract information from HTML documents</li><li><em>requests</em> is used to send HTTP requests and receive responses</li><li><em>pandas</em> is used for data manipulation and analysis</li></ul><pre>from bs4 import BeautifulSoup<br>import requests<br>import pandas as pd</pre><h3>Overview of HTML structure</h3><p>Understanding the HTML structure of a website is essential for web scraping, as it helps to identify the specific elements that need to be extracted.</p><p>In this project I am using London as the destination (<a href="https://www.booking.com/searchresults.en-gb.html?ss=London&amp;ssne=London&amp;ssne_untouched=London&amp;label=gog235jc-1DCAEoggI46AdICVgDaFCIAQGYAQm4ARfIAQzYAQPoAQH4AQKIAgGoAgO4ArDuuaEGwAIB0gIkZmJhYjE4YzAtNDdhMy00MmY1LTk2NWItN2UzOTgyNTk1OWEx2AIE4AIB&amp;aid=397594&amp;lang=en-gb&amp;sb=1&amp;src_elem=sb&amp;src=searchresults&amp;dest_id=-2601889&amp;dest_type=city&amp;checkin=2023-05-06&amp;checkout=2023-05-07&amp;ltfd=6%3A1%3A5-2023%3A&amp;group_adults=2&amp;no_rooms=1&amp;group_children=0&amp;sb_travel_purpose=leisure">link</a>)</p><p>It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBh_-ReEWkF8wnR3tcGHBA.png" /></figure><p>To inspect HTML elements on a web page, you can use the browser’s built-in developer tools. Here’s how to do it in Google Chrome:</p><ol><li>Open Google Chrome and navigate to the web page you want to inspect.</li><li>Right-click on the element you want to inspect and select “Inspect” or press the “Ctrl + Shift + I” (Windows/Linux) or “Cmd + Shift + I” (Mac) keyboard shortcut to open the Developer Tools panel.</li><li>In the Developer Tools panel, you’ll see the HTML source code of the web page. The element you right-clicked on should be highlighted in the Elements tab.</li><li>You can use the Elements tab to navigate the HTML tree and select any element you want to inspect. When you select an element, the corresponding HTML code will be highlighted in the panel, and you can view and edit its properties and attributes in the Styles and Computed tabs.</li></ol><p>Using the browser’s developer tools makes it easy to inspect and analyze the HTML structure of a web page, which is useful for web scraping projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*CQdCuxXjGTvnHOf8lYf3IQ.png" /></figure><h3>Getting HTML from a website</h3><p>To get the HTML from a website with Bootstrap, you can use Python’s requests library to send an HTTP request to the website’s server and retrieve the HTML content.</p><pre>url = &#39;https://www.booking.com/searchresults.html?ss=London&amp;ssne=London&amp;ssne_untouched=London&amp;label=gog235jc-1DCAEoggI46AdICVgDaFCIAQGYAQm4ARfIAQzYAQPoAQH4AQKIAgGoAgO4ArDuuaEGwAIB0gIkZmJhYjE4YzAtNDdhMy00MmY1LTk2NWItN2UzOTgyNTk1OWEx2AIE4AIB&amp;aid=397594&amp;lang=en-us&amp;sb=1&amp;src_elem=sb&amp;src=searchresults&amp;dest_id=-2601889&amp;dest_type=city&amp;checkin=2023-05-06&amp;checkout=2023-05-07&amp;ltfd=6%3A1%3A5-2023%3A&amp;group_adults=2&amp;no_rooms=1&amp;group_children=0&amp;sb_travel_purpose=leisure&amp;selected_currency=USD&amp;soz=1&amp;lang_changed=1&#39;<br>headers = {<br>    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36&#39;,<br>    &#39;Accept-Language&#39;: &#39;en-US, en;q=0.5&#39;<br>}<br><br>response  = requests.get(url, headers=headers)</pre><p>After retrieving the page we create a BeautifulSoup object by passing the HTML content and the desired parser (in this case, we’re using the ‘html.parser’ parser provided by BeautifulSoup)</p><pre>soup = BeautifulSoup(response.text, &#39;html.parser&#39;)</pre><p>The resulting soup object can be used to navigate the HTML tree and extract data from the web page.</p><p>From a list of hotels, we will retrieve the following information:</p><ul><li>Hotel name</li><li>Location</li><li>Price</li><li>Rating</li></ul><h3>Data Extraction</h3><pre># Find all the hotel elements in the HTML document<br>hotels = soup.findAll(&#39;div&#39;, {&#39;data-testid&#39;: &#39;property-card&#39;})<br><br>hotels_data = []<br># Loop over the hotel elements and extract the desired data<br>for hotel in hotels:<br>    # Extract the hotel name<br>    name_element = hotel.find(&#39;div&#39;, {&#39;data-testid&#39;: &#39;title&#39;})<br>    name = name_element.text.strip()<br><br>    # Extract the hotel location<br>    location_element = hotel.find(&#39;span&#39;, {&#39;data-testid&#39;: &#39;address&#39;})<br>    location = location_element.text.strip()<br><br>    # Extract the hotel price<br>    price_element = hotel.find(&#39;span&#39;, {&#39;data-testid&#39;: &#39;price-and-discounted-price&#39;})<br>    price = price_element.text.strip()<br>    <br>    # Extract the hotel rating<br>    rating_element = hotel.find(&#39;div&#39;, {&#39;class&#39;: &#39;b5cd09854e d10a6220b4&#39;})<br>    rating = rating_element.text.strip()<br>    <br>    # Append hotes_data with info about hotel<br>    hotels_data.append({<br>        &#39;name&#39;: name,<br>        &#39;location&#39;: location,<br>        &#39;price&#39;: price,<br>        &#39;rating&#39;: rating<br>    })</pre><h3>Creating a DataFrame</h3><p>Once you have extracted the desired data from a hotel list using Beautiful Soup, you can create a pandas DataFrame to store and manipulate the data.</p><pre>hotels = pd.DataFrame(hotels_data)<br>hotels.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*E8j8-2caKzNrOtIgNnF2bg.png" /></figure><h3>Creating a CSV file</h3><pre>hotels.to_csv(&#39;hotels.csv&#39;, header=True, index=False)</pre><h3>Done!</h3><p>To summarize, web scraping with Python and Beautiful Soup is a useful technique for extracting data from websites. In this project, I covered how to extract hotel data from Booking.com and create a CSV dataset from it.Thank you for reading this article! I hope it was helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f874820c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>