<?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 Madhura Ganguly on Medium]]></title>
        <description><![CDATA[Stories by Madhura Ganguly on Medium]]></description>
        <link>https://medium.com/@gangulym23?source=rss-36a67a2be67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*pKpMQxPSWc_jQD_qBnXISw.jpeg</url>
            <title>Stories by Madhura Ganguly on Medium</title>
            <link>https://medium.com/@gangulym23?source=rss-36a67a2be67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gangulym23/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[Pitfalls of MAPE as a forecast accuracy metric]]></title>
            <link>https://gangulym23.medium.com/pitfalls-of-mape-as-a-forecast-accuracy-metric-decff6877265?source=rss-36a67a2be67------2</link>
            <guid isPermaLink="false">https://medium.com/p/decff6877265</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[forecast-accuracy]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[mape]]></category>
            <dc:creator><![CDATA[Madhura Ganguly]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 16:15:37 GMT</pubDate>
            <atom:updated>2023-11-19T16:15:37.055Z</atom:updated>
            <content:encoded><![CDATA[<p>Despite being a very popular metric for measuring forecast accuracy in time series forecasting, MAPE certainly has its strengths and limitations that anyone using it should take into consideration.</p><figure><img alt="https://unsplash.com/photos/XC7lc8biINg?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash" src="https://cdn-images-1.medium.com/max/1024/1*U6szCUSAipfqEaNxlPx0vw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dancristianpaduret">Dan Cristian Pădureț</a> from <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>The main idea of this article to provide a deep review of efficacy of MAPE for measuring forecast accuracy in sales forecasting and inspect the metric’s behaviour in different scenarios. For scenarios where MAPE is not suitable, alternative metrics are discussed.</p><p>Let’s start by first defining MAPE or <strong>M</strong>ean <strong>A</strong>bsolute <strong>P</strong>ercentage <strong>E</strong>rror.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*8Tfg_NIfTdLfgWdMKtI-fQ.png" /><figcaption>MAPE</figcaption></figure><h3>Easy to interpret and scale independent</h3><p>There is no denying that MAPE has an easy interpretation which is probably why it is a popular metric for measuring forecast accuracy. For example, if MAPE for monthly demand forecasts of a product is 10% over last 12 months, it means that forecasts were wrong by 10% on an average over this time period. A low value of MAPE indicates high forecast accuracy and vice versa. MAPE is also scale independent, making it suitable for comparisons across different data sets.</p><p>But like all metrics MAPE has some deficiencies, let’s review what these are.</p><h3>1. MAPE is biased for very low sales and outliers</h3><p>Let’s review the four scenarios below to inspect how MAPE gets impacted by fluctuations in data. The underlying data has simulated sales values that mostly range between 1000 and 2000 units (ignoring the spikes and drops) and forecasts (a simple 3 point moving average) that also fall in similar range. At a glance, the forecasts seem to be doing a reasonably good job so MAPE could be expected to be reasonably good as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*AGU8S8H33Ir_wLiY4hWr5w.png" /><figcaption>How MAPE is influenced by fluctuations in sales and forecasts</figcaption></figure><p>In <strong>scenario 1</strong> (top left) actual sales drops to 20 for time point 5 and the corresponding absolute percentage error shoots up to 6000% (due to division by small value)! Though the rest of the time points incur reasonable APE (absolute percentage error) within range 0% to 60%, MAPE being an <strong>average gets influenced by the APE of 6000% which is an outlier and gets amplified to 312%. </strong>This drawback of MAPE has been discussed in Makridakis (1993)<em>.</em></p><p>Be it due to supply shortage or low demand, products with some periods of low sales are not uncommon, MAPE value gets dominated by these periods and portrays a biased forecast accuracy.</p><p>Ways to mitigate this issue are to either treat the actuals by imputing the outliers (low sales data points in this case) with regular sales or by ignoring such points altogether from MAPE calculation. However, it is always better not to distort the ground truth or leave out any information when assessing forecast accuracy. Another option is to report MAPE with and without outliers to retain all the information.</p><p>Alternatively MdAPE (Median Absolute Percentage Error) or <a href="https://docs.aws.amazon.com/forecast/latest/dg/metrics.html#metrics-WAPE"><strong>WAPE</strong></a> (Weighted Absolute Percentage Error) can be used instead of MAPE as these are more resistant to outliers.</p><p>WAPE is defined as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*9n7RuPHG42ez-hUojAxVJQ.png" /><figcaption>WAPE</figcaption></figure><p>where <em>n</em> is no. of forecasts. WAPE is also a scale free metric like MAPE but does not get bloated by particularly small sales values.</p><p><strong>Scenario 2</strong> (top right) illustrates how MAPE gets impacted by large outliers. When sales spikes up to 4000 for time point 5, we can see that while APE gets elevated around this time point, it does not get blown out of proportion like in scenario 1 and MAPE still appears to be unaffected.</p><p>Similarly, <strong>scenarios 3 and 4</strong> illustrate that similar fluctuations in forecasts do not have a significant impact on MAPE value.</p><h3>2. MAPE is infinite or undefined for intermittent sales</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*vvBtj3gyzCrltWqtFNX8Vg.png" /><figcaption>Intermittent sales data</figcaption></figure><p>When the need is to generate forecasts at a granular level, for example at product-store-daily grain, data often tends to run sparse with many time points having zero sales. Even when that is not the case there can be slow-selling products with intermittent sales or seasonal products with lumpy sales that are concentrated in certain periods of the year and zero for rest of the time points resulting in zero inflated time series. For such products MAPE is infinite (when forecast is non-zero) or undefined (when forecast is zero) and not a suitable metric for assessing forecast accuracy.</p><p>As an alternative to MAPE, Hyndman and Koehler (2006) proposed a scale free metric named MASE that scales forecast errors by the in-sample, one-step-ahead MAE of the Naïve method as the most suitable metric in case of intermittent sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*REdZfnsinmZJhG8RgjRl-g.png" /><figcaption>MASE</figcaption></figure><p>where <em>n</em> is the length of the series and <em>m</em> is its frequency, i.e., 1 for yearly data, 4 for quarterly, 12 for monthly, etc. Unlike MAPE, MASE does not get skewed by extremely small values or become infinite for zero inflated time series. However, the main disadvantage of MASE is interpretability. MASE of less than 1 indicates that forecasts are better than 1-step in-sample (training period) Naïve forecast and vice-versa, this can be hard to interpret in business terms and difficult to communicate to non-technical stakeholders.</p><p>Another metric was proposed by Petropoulos &amp; Kourentzes (2015) named sMAE (also stands for Scaled MAE) defined as follows, where the scaling factor is in-sample actuals sales mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*NCMmjVu6m94KC5kUQ4XdWA.png" /><figcaption>Scaled MAE</figcaption></figure><p>This measure is comparatively more intuitive than MASE but can be problematic in case of non-stationary data where mean of the series changes over time.</p><p><strong>WAPE</strong> looks similar to sMAE but has a different scaling factor, it is the total absolute actual sales from the forecast period and hence, does not have the same problem as sMAE and is suitable metric in case of intermittent sales.</p><h3>3. MAPE is asymmetric (is it ?)</h3><p>Makridakis (1993) has argued that the MAPE is asymmetric in that “equal errors above the actual value result in a greater APE than those below the actual value”. Similarly, Armstrong and Collopy (1992) argued that “Another disadvantage of the MAPE is that it puts a heavier penalty on forecasts that exceed the actual than on those that are less than the actual. For example, the MAPE is bounded on the low side by an error of 100%, but there is no bound on the high side.”</p><p>The evidence provided in Makridakis (1993) to demonstrate MAPE’s asymmetry is shown in the table below. We can see that that a negative error of 50 incurs a higher penalty than a positive error of 50.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*YlYiq5uk3SrzjRpbB5lCqA.png" /></figure><p>However, as pointed out in (Goodwin &amp; Lawton 1999) the difference in MAPE is not due to any asymmetry but due to actuals and forecasts getting swapped in the data making the actuals different in the 2 rows. If the actuals remain the same equal magnitude errors generate identical MAPE values irrespective of whether they are positive or negative as shown in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Opv1yUvFJ-aXs7zkFE-9cA.png" /></figure><p>So MAPE is not asymmetric in that sense. However, MAPE is unbounded for over-predictions which implies that large forecasts or over-predictions can have a much higher MAPE than small forecasts or under-forecasts. In case of under-prediction, worst case scenario is when forecasts become zero and this would result in MAPE of 100%. For over-prediction as forecasts can be as high as possible, and MAPE can also be as high as possible. Thereby, MAPE is asymmetric in this sense.</p><p><strong>Blindly optimizing for MAPE could result in choosing sub-optimal forecasts. </strong>For example, Table 1 below shows forecasts that are mostly over-predictions with total absolute error of 10,300 units and MAPE of 109%. Table 2 shows forecasts that are always 0 with total absolute error of 12,300 units and MAPE of 100%. In this case optimizing for MAPE could lead to choosing forecasts in table 2 which don’t serve any purpose and ignoring the forecasts in table 1 which have a lower absolute error.</p><p>Hence, MAPE should be used with caution and always be supplemented with additional metrics like MAE or RMSE. In contrast WAPE does not suffer from this problem and is a suitable scale free metric in this scenario as it correctly identifies the first forecast to have the lower error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IrN5mwXD090Oo_58BdZyrA.png" /><figcaption>MAPE vs WAPE</figcaption></figure><h3>4. MAPE is direction less</h3><p>Often there is trade-off between tolerance for over prediction error and under prediction error in supply chain demand planning. MAPE does not reflect direction of error as it is based on absolute errors.</p><p>For example, forecasts that overshoot actual product demand would result in excess inventory which not only entails storage cost but also run the risk of product obsolescence and subsequent loss of margin due to mechanisms that need to be run to deplete pending stocks. On the flip side, forecasts that under-predict actual product demand would result in stock-outs and loss of potential revenue due to unmet demand and subsequent dissatisfied customers who may go to competitors and not return.</p><p>If the tolerance and cost for each type of error is not the same MAPE is not useful in determining forecast accuracy, dissecting MAPE into over- prediction MAPE and under-prediction MAPE reveals error magnitude in each direction. Depending on business preference forecasts with better under prediction accuracy or over prediction accuracy can be chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rcQobzHTQp3EvIecNC4tcw.png" /><figcaption>Under forecast and Over forecast MAPE</figcaption></figure><p>We can also disaggregate WAPE into under-forecast and over-forecast error components as shown below. Taking in consideration the drawbacks discussed for MAPE, WAPE would be a better forecast accuracy metric that could be leveraged in this scenario as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GqU9PSV0R_ZDcXL3Ytv28A.png" /><figcaption>Under forecast and Over forecast WAPE</figcaption></figure><h3>Summary</h3><p>1. MAPE is intuitive to understand and suitable for making comparisons.</p><p>2. If there is a trade-off between tolerance for over prediction error and under prediction error, MAPE can be split into over-prediction and under-prediction components to prioritize either type of forecasts.</p><p>3. MAPE has a very skewed distribution for data with periods of low sales and is undefined or infinite in case of intermittent or lumpy sales. It should not be used in these cases.</p><p>4. Though MAPE equally penalizes positive and negative errors of equal magnitude, it is unbounded for over-predictions which may cause MAPE to be smaller for forecasts that are dominated by under-predictions. Optimizing forecast accuracy using MAPE could result in selection of conservative forecasts.</p><p>5. <strong>WAPE is a scale free metric that is a great alternative to MAPE as it does not share the concerns highlighted for MAPE but has similar strengths as MAPE.</strong></p><h3><strong>Acknowledgement</strong></h3><p>I would like to thank Shams Kazmi for reviewing and providing his valuable suggestions for this article.</p><h4>References</h4><p>1. Armstrong, J. Scott, and Fred Collopy. 1992. “<strong>Error Measures for Generalizing about Forecasting Methods: Empirical Comparisons</strong>.” <em>International Journal of Forecasting</em> 8(1). doi:<a href="https://doi.org/10.1016/0169-2070%2892%2990008-W"> https://doi.org/10.1016/0169-2070(92)90008-W</a>.</p><p>2. Goodwin, Paul, and Richard Lawton. 1999. “<strong>On the Asymmetry of the Symmetric MAPE.</strong>” <em>International Journal of Forecasting</em> 15(4):405–8. doi:<a href="https://doi.org/10.1016/S0169-2070%2899%2900007-2"> https://doi.org/10.1016/S0169-2070(99)00007-2</a>.</p><p>3. Hyndman, Rob. 2006. “<strong>Another Look at Forecast Accuracy Metrics for Intermittent Demand</strong>.” <em>Foresight: The International Journal of Applied Forecasting</em> 4:43–46. doi : <a href="https://doi.org/10.1016/j.ijforecast.2006.03.001">https://doi.org/10.1016/j.ijforecast.2006.03.001</a>.</p><p>4. Makridakis, Spyros, 1993. “<strong>Accuracy measures: theoretical and practical concerns</strong>,” International Journal of Forecasting, Elsevier, vol. 9(4), pages 527–529, December. doi : <a href="https://doi.org/10.1016/0169-2070%2893%2990079-3">https://doi.org/10.1016/0169-2070(93)90079-3</a>.</p><h4>Related articles</h4><p>1. <a href="https://medium.com/bcggamma/demand-forecasting-evaluation-691824c70f02">https://medium.com/bcggamma/demand-forecasting-evaluation-691824c70f02</a></p><p>2. <a href="https://towardsdatascience.com/time-series-forecast-error-metrics-you-should-know-cc88b8c67f27">https://towardsdatascience.com/time-series-forecast-error-metrics-you-should-know-cc88b8c67f27</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=decff6877265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This is how you can analyze any dataset with the CRISP-DM framework]]></title>
            <link>https://gangulym23.medium.com/this-is-how-you-can-analyze-any-dataset-with-the-crisp-dm-framework-cc9353f4dabe?source=rss-36a67a2be67------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9353f4dabe</guid>
            <dc:creator><![CDATA[Madhura Ganguly]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 16:48:31 GMT</pubDate>
            <atom:updated>2021-04-15T05:59:55.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Airbnb Boston data with CRISP-DM framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOvvpd8QtALncxB58NmAfA.jpeg" /></figure><h3>Overview</h3><blockquote>CRISP-DM stands for <strong>Cross Industry Standard Process for Data Mining </strong>and is a widely accepted framework for data exploration and analysis in the data science community.</blockquote><p>In this post I have outlined the key steps of the CRISP-DM framework and showcased how this can be applied to any data analysis project. The data used for this project is the <strong>Airbnb Boston Listings Data, </strong>all<strong> </strong>the datasets are available <a href="http://insideairbnb.com/get-the-data.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUGylLDVyFBAGFZNMtw6Ig.png" /></figure><p>The datasets mentioned above are analyzed to find answers to the following questions about the Airbnb listings in Boston :</p><ul><li><em>How do listing prices change across locations and time ?</em></li><li><em>What are the main drivers of listing price ?</em></li><li><em>What features of a listings influence customer satisfaction the most ?</em></li></ul><p><em>Lets get started !</em></p><h4>Data Description</h4><p>These are 3 datasets from Airbnb Boston that have been analyzed :</p><ul><li><em>listings.csv — </em>details on listing features like location, amenities and reviews</li><li><em>calendar.csv</em> — availability calendar of listings over a one year period</li><li><em>reviews.csv</em> — reviews posted by customers after their stay</li></ul><p>In the rest of the article we have analyzed these datasets following the <strong>CRISP-DM</strong> approach to find answers to the questions proposed in the overview section. The notebook with all analysis can be found <a href="https://github.com/maddyg/Data-Scientist-Nanodegree/tree/master/Project1-Write_a_Data_Science_Blog">here</a>.</p><h4>Step 1 : Business Problem Understanding</h4><p>Typically, this step involves working sessions with business teams for understanding the problems we are trying to solve with data. That is not feasible for this project. <br>There can other be scenarios where the <strong>data needs to be analyzed first</strong> to understand what questions about business processes can be answered from it. This is the scenario we are in and I have first analyzed the datasets to understand how they are structured and what information is contained in them and then proposed the questions.</p><p>Depending on the data science maturity of a company we may find ourselves in either of the two situations.</p><h4><strong>Step 2 : Data Understanding</strong></h4><p>In this step we start understanding the data, like, the meaning of the columns in the data and how they get generated. We can form a better understanding of the data if we can link the column meanings to the data.</p><p>For this we create summary reports from the raw datasets. The summary report provides an overview of the data like -</p><ul><li># of rows and columns</li><li>data type each column</li><li># unique values in each column</li><li># missing values in each column</li><li>summary statistics like mean, median and standard deviation for numeric columns</li><li>Date range for date columns</li></ul><p>This is the summary report created for the calendar data. For example, listing_id is the unique id provided to every listing registered on Airbnb and we see from the report there are 3585 unique listings in Boston. This is how we can form both qualitative and quantitative view of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFFRZfJpFQxlFNvegzLVUw.png" /></figure><h4>Step 3 : Data Preparation</h4><p><em>Data preparation</em> is the whole gamut of manipulations and transformations performed on data to tackle inconsistencies like missing values or outliers, convert columns to the right format or enrich data with new features.</p><p>The summary report created above helps to identify data inconsistencies like incorrect data types and missing values. For example, from the image above we can see that price has has been read as a string due to embedded $ sign and has 665,853 missing values.</p><p>These are the key data preparation steps that are usually applied on any dataset :</p><ul><li><strong>convert columns to correct data types</strong></li><li><strong>drop identical duplicates rows</strong></li><li><strong>drop columns with constant values</strong></li><li><strong>impute missing values</strong></li><li><strong>encode categorical features</strong></li></ul><p>For calendar data -</p><ul><li>price is converted to numeric data type</li><li>365 identical duplicate records are dropped</li></ul><p>For listings data -</p><ul><li>Features like price , host_response_rate, extra_people, security deposit are converted to numeric data types.</li><li>neighbourhood_group_cleansed, has_availability license, requires_license and jurisdiction_names have 100% values missing and are dropped.</li><li>Many features have missing values in this dataset, some of them being review_scores_communication, review_scores_accuracy , bathroom, review_scores_checkin, accommodates .</li><li>If more than 90% of values are missing they are not imputed and the column is not used for analysis. <strong>For numeric columns, missing values are imputed with local median and for categorical columns, missing values are imputed with “missing” text</strong> and encoded later on.</li><li>Most of the machine learning algorithms can only work with numeric data, this is why all categorical and object data fields first need to be encoded into numeric values first.</li><li>Categorical features that are nominal like property_type, neighbourhood_cleansed, room_type are encoded<strong>. </strong>Categorical features with 10 or less categories are encoded with<strong> One Hot Encoding </strong>and those with higher number of unique categories are encoded with Binary encoding.</li></ul><p>Once the dataset has been prepped through the above steps we can explore the distribution of individual features and between feature.This is known as <strong>Exploratory Data Analysis</strong>. This step often leads to more data preparation steps as we discover better ways to represent the data.</p><p>We might also create new features based on domain knowledge if we feel that will improve quality of insights and models and make them easier to be consumed by business. This step is known as <strong>Feature Engineering</strong>.</p><p><strong>Feature transformation</strong> steps like scaling or log transformation are also done before applying supervised or unsupervised learning algorithms on the dataset. These steps are usually needed for linear models and distance based clustering approached (like KMEANS) to help with the algorithm convergence process.</p><p>Depending on requirement, <strong>Data preparation, Exploratory data analysis and Feature engineering</strong> are often done several times in the course of a data science project.</p><p>Some of the highlights from <strong>Exploratory data analysis </strong>on Airbnb data<strong>:</strong></p><ul><li><strong>price</strong> has a very positively skewed distribution and mostly range between $50-$500 though there are some extremely high values that go over $1000.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*RuWctp69ZW5naRFxifsuRA.png" /></figure><ul><li><strong>Entire homes/ apartments</strong> make up almost 60% of the Airbnb listings in Boston followed by private homes, shared rooms have roughly 2% share.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BS5TfEmxG6K_NX8EUxM1Qg.png" /></figure><ul><li>Majority of the listings are <strong>apartments</strong> followed by <strong>houses and condominiums.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*YmpgqCEfYRdKDnEN32deQA.png" /></figure><ul><li><strong>Only 11% of the hosts are given the Super host status by Airbnb</strong>. To become a Super host a host needs to maintain 90% response rate or higher, 4.8 overall rating , 1% percent cancellation rate or lower and at least 10 completed trips OR 3 completed reservations that total at least 100 nights.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*xOCbuYrO3JNEjD0WVbazlg.png" /></figure><ul><li><strong>The 3 different room types have very distinct prices ranges</strong>. Entire homes and apartments are usually most expensive with median price around $200 but as we can see from the box plot below there is a wide range of prices available. Private rooms have a median price of roughly $90 and shared rooms are most economical with median price of $50.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*8Z_Z33R95rgSQDRCQh37Kw.png" /></figure><ul><li><strong>Cancellation policy is stricter for the more expensive listings</strong>. This is probably because in the event of cancellation the loss incurred by hosts is higher for more expensive listings and the cancellation policy is a means to attract customers who are sure of their travel plans.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*yfgdWc6Vtno07uIcODRgeg.png" /></figure><ul><li>As expected <strong>super-hosts have a higher median review rating score</strong> as compared to regular hosts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*SB5dSEd_cpUzK_qY3byFog.png" /></figure><ul><li><strong>Super hosts have much higher median reviews</strong> as they have higher completed reservations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PnAirAgaOJUtM-xYgkxVpg.png" /></figure><ul><li><strong>Almost all super-hosts have almost 100% response rate.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*EW2_RSRTCtU32NmRVZYaDQ.png" /></figure><h4>Step 4 : Modeling and Evaluation</h4><p>Depending on the problem we are solving for the solution could be framed as a machine learning model. The quantity of interest is usually treated as the <strong>Target variable or Dependent variable</strong> and all other information as <strong>Predictor variables or Independent variables</strong>.</p><p>For model driven solutions, the model output could be used in different ways.</p><ul><li>Use model predictions to drive business processes, example — demand forecasting, recommender systems, search ranking</li><li>Use model feature importance to understand the key drivers of prediction, for example — listing attributes that influence customer satisfaction or occupancy rate at Airbnb listings.</li></ul><p>One of the key factors for a machine learning model to be actionable is for it to generalize to unknown data with high precision, without that the model has no value. The process of determining whether a predictive model possesses this quality in known as <strong>Model Validation</strong>.</p><p>In this step the model performance on <strong>Training data</strong> —<em> data on which model is built</em> and <strong>Test data — </strong><em>data the model has not been exposed</em> <em>to</em> are evaluated.</p><h4>Step 5: Communicate Results</h4><p>This is where we share our findings from data analysis and modeling to (usually non-technical) audience.</p><h3>How do listing prices change across locations and time ?</h3><p>Let’s look at the median prices of listings by Boston neighborhoods.</p><ul><li>Hyde Park, Mattapan and Dorchester seem to be most economical locations where the median price is in the range of $50 — $100. These neighborhoods are in the suburbs away from Downtown.</li><li>On the other end of the spectrum are the neighborhoods of Bay Village, West End and Leather District where median prices are the range of $300-$400. These neighborhoods are close to downtown and popular tourist attractions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*fpzAtp98vOtcXnwW_RVOvw.png" /></figure><h4>Seasonality in price</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*vPDSuMRU4_U-rp6-Bj0STg.png" /></figure><ul><li>The general trend shows that festive period and winter season between November and March are not a good time for business. This is probably because during this time people usually celebrate with family and stay home and winters are pretty chilly in Boston and probably not the best time to visit.</li><li>June to October seems to be the best time to visit Boston and a similar pattern can be seen from the data. Prices start increasing from April with the onset of spring and remains high through May to October. This is probably due to the increased demand with more tourists visiting Boston during this time.</li><li>Comparing prices between 2016 and 2017, average prices were higher in 2016 September and compared to 2017 September.</li><li>Variance in prices, as indicated by the light blue shaded region in the chart above, increases during the spring and summer, this is probably because the busier listings increase their price more than others.</li></ul><h4><strong>Seasonality in price within suburbs and downtown</strong></h4><p>As we can see in the charts below, prices do not vary much across time in the suburbs, probably due to less fluctuation in demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*hLQOS3SQdc7ZT_m9NYVmRA.png" /></figure><p>Prices show similar seasonality pattern as seen at the overall level with prices falling between November to March and rising from April onward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*1M2fqKAsMiHCE71KqWP0Aw.png" /></figure><h4>Weekly seasonality in price</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*cUl4PIzlY4rj02ZIcMF4wA.png" /></figure><ul><li>Prices start increasing from Thursday and reach a peak over Friday and Saturday and fall on Sunday, this could be due to most tourists coming in mid-week close to the weekend and ending their stay on a Sunday to be back to work from Monday.</li></ul><h3><em>What are the main drivers of listing price ?</em></h3><p>Knowing the factors that drive price charged by listings can be utilized by hosts to enhance or add new amenities and services at their listings and be able to charge a higher price based on what similar listings charge.</p><p>For example — as we shall see in the section below, number of beds available in a listings is a driver of price, a host might be able to charge a bit more by adding an extra bed if there is space.</p><p>For this part I have built a machine learning model that predicts listing price- (<em>target variable</em>) based on listing features like location, no. of bedrooms, room type, property type etc. (<em>predictor variable</em>).</p><p>The features that come out to be most important are then analyzed and visualized to understand their relationship with price.</p><p>On the flip side the model predictions can also be leveraged by new hosts to have a market estimate of what price they can charge based on the location and amenities available at their listing.</p><p><strong><em>Some details on the model</em></strong></p><blockquote>Model Type — <em>Regression model</em></blockquote><blockquote>Algorithm used — <em>xgboost</em></blockquote><blockquote>Target variable — price</blockquote><blockquote>Predictor variables — All numeric features excluding price related features like weekly price, monthly price.</blockquote><blockquote>Hyper-parameter tuning — Grid search using 5 fold cross validation</blockquote><blockquote>Evaluation metric — R² and RMSE</blockquote><blockquote>Model Performance —</blockquote><blockquote>R² — Train set : 0.63 | Test set : 0.55</blockquote><blockquote>RMSE — Train set : 77 | Test set : 78</blockquote><p>These are the top 20 important features that come out from the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*UFSBAuvOw04Y9L-Qdl85Kw.png" /></figure><h4>Interpreting the top drivers of price</h4><ol><li><strong>Room Type = “Private room”</strong></li></ol><ul><li>From the plot below we can see that private room prices are very different from non-private room prices. For private rooms median price is about <strong>$80</strong> while for non-private rooms it is <strong>$199.</strong></li><li>As observed from bi-variate analysis before room_type is an important indicator of price, entire homes or apartments are more expensive, followed by private rooms and shared rooms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*vwfzomJQv2LCQ4wOlAiJIQ.png" /></figure><p><strong>2. Cleaning Fee</strong></p><ul><li>From the plot below we can see that listings prices increase with cleaning prices. Median price for listings with cleaning fee less than $50 is <strong>$95</strong>, listings with cleaning fee between $50-$100 have median price of <strong>$200 </strong>and listings with higher cleaning fee have median price of <strong>$250</strong>.</li><li>As we can see from the last box-plot there is a small group of listings that charge $200-$300 for cleaning and are priced below $200.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*crBnJ1o9NQAiRZpk9MGRLQ.png" /></figure><p><strong>3. No. of bedrooms</strong></p><ul><li>From the plot below we can see that listings prices increase with number of bedrooms. Median price for listings with 1 bedroom is <strong>$103</strong>, listings with 2–3 bedrooms have median price of<strong> $250 </strong>and listings with 4–5 bedrooms have median price of <strong>$375</strong>.</li><li>For entire homes and apartments this is expected as more bedrooms mean more square footage and bigger places which naturally cost more.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*nx2IPQUViWPseiFiP5JjsQ.png" /></figure><p><strong>4. No. of bathrooms</strong></p><ul><li>Price distribution is quite different for different no. of bathrooms and prices are higher for places with more no. of bathrooms. Median price for listings with 1 bathroom is <strong>$140</strong> and median price for listings with 2–3 bathrooms is<strong> $199,</strong> as number of bathrooms increase to 4–5, median price goes up to <strong>$325</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*TZFx-aQYqohnn9H7eehTuw.png" /></figure><p><strong>5. Accommodates</strong></p><ul><li>Listing prices increases sharply with number of people it accommodates. Median prices goes from <strong>$65 to $125</strong> as people accommodated increases from 1 to 3, while listings that can accommodate 4–5 people have median price of<strong> $200</strong> and those that can accommodate more than 5 people have median price of <strong>$267</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*5eG-HuvYERR3WGvw6dsjFg.png" /></figure><p><strong>6. Review score location</strong></p><ul><li>High location score is an indicator of a good location and it is no surprise that high location score means pricier listings.</li><li>As we can see from the chart below, listings with a location score of less than 7 have median price of <strong>$70.5 </strong>and those with location score between 7–9 have median price of <strong>$100</strong>, for the highest score location median price is $175 and the upper range of prices goes beyond<strong> $400</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*bFFHnYLGjvfYsu5wc1RoRw.png" /></figure><p>The amenities which turned up as important features are :</p><ul><li>TV</li><li>cable</li><li>heating</li><li>internet</li><li>pets allowed on property</li><li>elevator</li></ul><h3><em>Which listing features influence customer satisfaction the most ?</em></h3><p>Knowing what makes guests happy can help the hosts improve their customer experience which creates a win-win for the whole ecosystem, customers are happy and leave good reviews, host gets more business, Airbnb gets more business and happy customers.</p><p>Airbnb guests can provide review scores on many parameters like cleanliness, value, accuracy, check-in experience, location and overall. The overall rating review_score_rating can be thought of as a measure of overall customer satisfaction as the rest of the scores are very specific to certain aspects of the experience.</p><p>To find out which features influence customer satisfaction I have built a machine learning model that predicts the review_scores_rating- (<em>target variable</em>) based on listings features like location score, cleanliness score, price, number of reviews, etc.(<em>predictor variable</em>).</p><p>The features that come out to be most important are then analyzed and visualized to understand their relationship with review_score_rating .</p><p><strong><em>Some details on the model</em></strong></p><blockquote>Model Type — <em>Regression model</em></blockquote><blockquote>Algorithm used — <em>review_score_rating</em></blockquote><blockquote>Target variable — review_score_rating</blockquote><blockquote>Predictor variables — All numeric features excluding host_is_superhost</blockquote><blockquote>Hyper-parameter tuning — Grid search using 5 fold cross validation</blockquote><blockquote>Evaluation metric — R² and RMSE</blockquote><blockquote>Model Performance —</blockquote><blockquote>R² — Train set : 0.85 | Test set : 0.73</blockquote><blockquote>RMSE — Train set : 2.8| Test set : 3.61</blockquote><p>These are the top 20 important features that come out from the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*dgXpk5Q7yWSWW9uTpJsndA.png" /></figure><ol><li><strong>Review scores cleanliness</strong></li></ol><ul><li>As we can see from the chart below,review_scores_rating increases sharply with review_scores_cleanliness. This shows that ensuring a clean place is probably the most important factor to customer satisfaction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*kjFVpiQ27nxyn2PZ98SNGw.png" /></figure><p><strong>2. Review scores value</strong></p><ul><li>From the chart below we can see that review_scores_value has a strong positive correlation with review_scores_rating. This shows customers who feel that the listing is good value for money leave a high overall review score rating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*Qgc8JlySz5wp-faYlVFS2g.png" /></figure><p><strong>3. Review scores accuracy</strong></p><ul><li>As we can see from the chart below, listings with review_scores_accuracy also have high review_scores_rating. This shows that when customers book a listing based on nice looking online photos and descriptions and the reality turns out to be not so nice, customer satisfaction and rating might be affected.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*uM-hIL8vPJh4CQKTtOBJ4g.png" /></figure><p><strong>4. Review communication score</strong></p><ul><li>Communication between host and customers is key ! Listings with high review_scores_communication also have high review_scores_rating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*z_K7ac0tvuLoy90_zcBzvw.png" /></figure><p><strong>5. Review score check-in</strong></p><ul><li>review_scores_checkin is the 5th most important predictor of review_scores_rating. The chart below shows that customer check-in experience plays an important role in in getting a high rating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*M5EHqUl7-eYYlbGQw89Qig.png" /></figure><p>Amenities that seem to influence review_scores_rating are :</p><ul><li>Internet</li><li>Washer</li><li>Dryer</li><li>Cable</li><li>Gym</li><li>Elevator</li></ul><p>In case of these amenities, usually their presence is associated with higher customer rating. For example, as we can see in the table below having a dryer available increases chances of getting a <strong>high rating in range of 90–100 by 10% !</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*oyfYIkhcqlyjWWchkeeM0g.png" /></figure><p><strong>Step 6 : Deployment</strong></p><p>This is the step where all the analysis and modeling done before are put to action. It could mean the model built is put into production or the insights shared are factored into business decision making.</p><p>These are the key steps in the CRISP-DM framework. Analyzing any new dataset can be quiet challenging but following the steps outlined in this framework can bring structure to the process.</p><p><a href="https://github.com/maddyg/Data-Scientist-Nanodegree/tree/master/Project1-Write_a_Data_Science_Blog">Here</a> is the link to the GitHub repository for this analysis.</p><p>Thank you for reading the article and I hope you have found it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc9353f4dabe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple guide to Bias-Variance Trade-off — Part 1]]></title>
            <link>https://medium.com/analytics-vidhya/a-simple-guide-to-bias-variance-trade-off-part-1-2418229c78e0?source=rss-36a67a2be67------2</link>
            <guid isPermaLink="false">https://medium.com/p/2418229c78e0</guid>
            <category><![CDATA[underfitting]]></category>
            <category><![CDATA[bias-vs-variance]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[bias-variance-tradeoff]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Madhura Ganguly]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 08:33:20 GMT</pubDate>
            <atom:updated>2020-04-29T16:19:45.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>A simple guide to Bias-Variance Trade-off — Part 1</h3><h4>A quick refresh of the main concepts of bias-variance trade off for model building.</h4><figure><img alt="What the heck Bias-Variance Tradeoff is??? – mc.ai" src="https://cdn-images-1.medium.com/proxy/1*k_D4-U7c3Tf8hJRpaOZoBQ.png" /></figure><p>The above image showing the 4 scenarios of bias variance mix is very common when trying to explain bias-variance trade-off.</p><h3>But what is bias and variance ?</h3><p>The aim of a good model is to have low bias and low variance. If we can know which scenario our model suffers from then we can apply the appropriate solution to reach the low bias and low variance quadrant.</p><p>The explanation to these concepts are often highly technical but we shall only keep to the intuition here.</p><p><strong>Bias </strong>quantifies the gap between the <strong>average model fit</strong> between the target variable and predictor variables and the <strong>true relationship </strong>between the target variable and predictor variables.</p><p>This is why missing important features from the model or considering a functionally simple model often results in a high bias model as the <strong>average model </strong>fit ends up being different from the true relationship. This is also known as <strong>Under-fitting.</strong></p><p><strong>Average model fit</strong> — If we drew a large number of training samples (let this number be denoted by S) from the population of all observations and obtained the model fit for each training sample, we would have S model fits and S fitted values for each observation in the population. The average across the S fitted values is known as the average model fit.</p><p><strong>Variance </strong>quantifies<strong> </strong>the spread of the model fits around the <strong>average model fit.</strong> Hence, if the model fits vary a lot around the <strong>average model fit</strong> across the training samples this indicates we have a high variance model.</p><p>Complex models, especially with small samples often lead to high variance models. This is also known as <strong>Over-fitting</strong>.</p><h3>Symptoms and Remedy</h3><p><strong>When building a machine learning model we would not be able to compute the bias and variance values to diagnose which quadrant we fall in</strong>. <strong>We can only detect this by analyzing our model training and test errors.</strong></p><blockquote>Let’s try to understand the following for each of the 4 scenarios when building a machine learning model :</blockquote><blockquote>1.What are the symptoms for detecting each scenario ?</blockquote><blockquote>2.What causes them and what’s the solution ?</blockquote><h3>Symptom</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nf2KhxCozv1f9tHJE1mcSA.png" /></figure><h3>Cause and Remedy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdQvASqVQa--30WxfnN7pA.png" /></figure><h3>Bias-Variance Trade-off Decision Routes</h3><p>Between the first model we build and the final model we traverse different decision routes till we strike the right balance between bias and variance.</p><p>Here are the different bias-variance trade-off routes for going from <strong>Low bias-High variance to Low bias -Low variance :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*27i-d1V4oz-mrUmBao8MOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vL1qpptaW_38MVrna2taLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*24rjzQX2Qje4bEEY9mIzZA.png" /></figure><p>Here are the different bias-variance trade-off routes for going from <strong>High bias-High variance to Low bias -Low variance :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9dKgoqP3APLfov2EDkLOhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SMkFLDh5Tv7b4vfxCH5eQA.png" /></figure><p>Here are the different bias-variance trade-off routes for going from <strong>High bias-Low variance to Low bias -Low variance :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*butvrMsYYTJITqaUkBEAAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7ZHCoKWRDHCpmeoS-sd7OQ.png" /></figure><p>That’s all for Part-1. In the next part of this article we explore the relationships between training error, test error and model complexity, training sample size.</p><h3><strong>Thank you for reading this article !</strong></h3><h4>References:</h4><ol><li><a href="https://www.coursera.org/learn/ml-regression">Regression course in Machine Learning Specialization from University of Washington on Coursera.</a></li><li><a href="http://scott.fortmann-roe.com/docs/BiasVariance.html">Understanding the Bias-Variance Tradeoff</a></li><li><a href="https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote12.html">Lecture 12: Bias-Variance Tradeoff</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2418229c78e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-simple-guide-to-bias-variance-trade-off-part-1-2418229c78e0">A simple guide to Bias-Variance Trade-off — Part 1</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Pandas  — Part 2]]></title>
            <link>https://medium.com/analytics-vidhya/practical-pandas-part-2-9ebacf682678?source=rss-36a67a2be67------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ebacf682678</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data-manipulation]]></category>
            <dc:creator><![CDATA[Madhura Ganguly]]></dc:creator>
            <pubDate>Sat, 14 Sep 2019 07:39:18 GMT</pubDate>
            <atom:updated>2019-10-03T09:07:57.023Z</atom:updated>
            <content:encoded><![CDATA[<h3>Practical Guide to Pandas Essentials for Beginners</h3><h4>A tutorial to pick up key pandas skills for those starting out with this most important data analysis library.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnkmEPaguuMBQdvGwtzfWw.jpeg" /></figure><p>This is the second article in a series on learning practical applications of Pandas library without getting overwhelmed by too many details. This is meant for those who are new to pandas and want to learn the how to perform the most common data analysis tasks quickly. Hence, this series is going to cover the details needed to launch your pandas learning without going over everything that can be done with pandas.</p><p>The Jupyter notebook can be accessed from GitHub and also available at the end of this tutorial. I would encourage you to download the notebook and follow along by running the script.</p><p>This tutorial covers</p><ol><li>Selecting rows and columns</li><li>Change values of a dataframe</li><li>Appending dataframes</li><li>Handling duplicates</li><li>Handling missing values</li><li>Changing columns types</li></ol><h3>Quick recap on last tutorial</h3><p>In <a href="https://medium.com/@gangulym23/practical-pandas-50586fe90cf8"><strong>last tutorial</strong></a> we have covered basic data operations like read, write, adding new column, re-coding existing columns and dropping column. Here is the <a href="https://github.com/maddyg/Practical-Pandas-Learning/blob/master/Practical%20Pandas%20-%20Part%201.ipynb"><strong>github link</strong></a> to the jupyter notebook. Also posted below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3763d655082d447dded55c484a6bd887/href">https://medium.com/media/3763d655082d447dded55c484a6bd887/href</a></iframe><h3>Create Dataset</h3><p>First of all let’s create the dataset for this tutorial, this is the same iris dataset used in the last tutorial.</p><pre><strong><em># import libraries</em></strong><br>import pandas as pd<br>from sklearn import datasets</pre><pre><strong><em>#creating the dataset for this tutorial</em></strong><br>iris = datasets.load_iris()<br>print(“Iris data shape :”, iris[‘data’].shape)<br>df=pd.DataFrame(iris.data,columns=iris.feature_names)<br>df[‘target’]=iris[‘target’]</pre><pre><strong><em># Use map to recode column</em></strong><br>species_mapping=<br>{<br>0:iris[‘target_names’][0],<br>1:iris[‘target_names’][1],<br>2:iris[‘target_names’][2]<br>}<br>print(‘Checking species mapping: ‘)<br>print(species_mapping)<br>print(‘\n’)</pre><pre>df[‘Species’] = df[‘target’].map(species_mapping)<br>print(“Checking if Species is created : “)<br>print(df.head())<br>print(‘\n’)</pre><pre><strong><em>#show few records</em></strong><br>print(df.head())</pre><p>Voila! Our dataset is ready to go with 150 rows and 4 columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_Q2BZaai3oK864qRCheIw.png" /></figure><h3>Selecting rows and columns from data frame</h3><p>One of the most common data tasks we perform are selecting subsets of data either by selecting set of rows or columns or combination of both. This can be a bit tricky (and frustrating) in pandas unless we know what’s happening behind the scenes. Let’s see how we can accomplish these tasks in pandas.</p><h4>.iloc and .loc</h4><p>.iloc and .loc are indexers that are used for selecting rows and columns in pandas, .<strong>iloc can be used to select rows or columns by number</strong> and <strong>.loc can used to select rows with row labels or boolean masks</strong>. Note, that the dataframe created above has row numbers as row labels, this is the default row index when no column is assigned to be the row label of a pandas dataframe. Lets learn with some examples.</p><pre><strong># select 1st row using .iloc<br></strong>print(&quot;\n&quot;)<br>print(&quot;Select row 1 using iloc (returns series) :&quot;)<br>df.iloc[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*5YvnfmxBU-LKsx9oayEtCQ.png" /></figure><p>This is how we can get the first row of a dataframe by using <strong>.iloc</strong>. Notice that this returns a series object and not a dataframe, which is often not what we need. Let’s see how to get a dataframe.</p><pre><strong># select 1st row using .iloc</strong><br>print(“\n”)<br>print(“Select row 1 using iloc (returns dataframe) :”)<br>df.iloc[[0],:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*uEKpnb9SujJxNPHbxzaBMA.png" /></figure><p>Now, this returns the first row as a dataframe. The same applies for selecting columns, use double brackets when you need a dataframe.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#select 1st column using loc<br></strong>print(“\n”)<br>print(“Select 1 column using .loc (returns series) :”)<br>df.loc[:,’sepal length (cm)’]</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*2lbSUfUBKJimzMaWthRTEA.png" /></figure><blockquote><strong>CODE</strong></blockquote><pre><strong>#select 1st column using iloc</strong><br>print(&quot;\n&quot;)<br>print(&quot;Select column 1 using using iloc (returns dataframe) :&quot;)<br>df.iloc[:,[0]]</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*J72IyQhjBQZXFrc4mBw4VA.png" /></figure><blockquote><strong>CODE</strong></blockquote><pre><strong>#select 1st column using iloc<br></strong>print(&quot;\n&quot;)<br>print(&quot;Select column 1 using using iloc (returns dataframe) :&quot;)<br>df.iloc[:,[0]]</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*vkupEUnXWsADI25gThPHPw.png" /></figure><p>We can also select multiple rows and columns with .iloc.</p><pre><strong><em>#select multiple rows using iloc</em></strong><br>df.iloc[0:5] #returns a dataframe<br>df.iloc[0:5,:] #returns a dataframe</pre><pre><strong><em>#select multiple columns using iloc</em></strong><br>df.iloc[:,0:3] #returns a dataframe</pre><pre><strong><em>#select rows and columns with iloc</em></strong><br>df.iloc[0:5,0] #returns a series<br>df.iloc[0:5,[0]] #returns a dataframe<br>df.iloc[0:5,0:3] #returns a dataframe</pre><p>Now, lets see how to do the same operations using <strong>.loc</strong>.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#select 1st row using loc<br></strong>print(“\n”)<br>print(“Select 1 row using loc (returns series) :”)<br>df.loc[0] <br>df.loc[0,:]</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*MpqJeoG71m7TjQkkHAADIg.png" /></figure><blockquote><strong>CODE</strong></blockquote><pre><strong>#select 1st row using loc<br></strong>print(“\n”)<br>print(“Select 1 row using loc (returns dataframe) :”)<br>df.loc[[0],:] # returns a dataframe, not specifying colunms returns all columns</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*PW_eyecBcL8hqbBmqkCpTA.png" /></figure><blockquote>CODE</blockquote><pre><strong># select 1st column using loc<br></strong>print(“\n”)<br>print(“Select 1 column using loc (returns series) :”)<br>df.loc[:,’sepal length (cm)’]</pre><blockquote>OUTPUT</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*vcIV7eaS9di9pARrdVIzDw.png" /></figure><blockquote><strong>CODE</strong></blockquote><pre><strong># select 1st column using loc<br></strong>print(“\n”)<br>print(“Select 1 column using loc (returns dataframe) :”)<br>df.loc[:,[‘sepal length (cm)’]]</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*lBKw_BCYmwEmVLVdZg093A.png" /></figure><p>We can also select multiple rows and columns with .loc.</p><pre><strong><em>#select multiple rows using loc<br></em></strong>df.loc[0:5,:] # returns a dataframe</pre><pre><strong><em>#select multiple columns using loc<br></em></strong>df.loc[:,[‘sepal length (cm)’,’sepal width (cm)’]] </pre><pre><strong><em>#select rows and columns with loc<br></em></strong>df.loc[0:5,[‘sepal length (cm)’]] <br>df.loc[0:5,[‘sepal length (cm)’,’sepal width (cm)’]] </pre><p>Next, the most commonly used selections we work with are conditional selections, for these we need to use .loc.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#select rows with conditions using loc<br></strong>bool_mask = df[‘sepal length (cm)’]&gt;4 <br>df.loc[bool_mask]</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*VdcOhr78JWxcY5auOIOKxA.png" /></figure><p>Note the difference when using numbers to select rows with iloc and loc, iloc works like regular python indexing but loc does not.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#Note the difference</strong></pre><pre><strong>#loc returns all rows 0 to 5 with matching labels<br></strong><em>print(&quot;.loc&quot;)<br>print(df.loc[0:5,[‘target’]])</em></pre><pre><strong>#iloc returns rows 0 to 4, just like regular python indexing in lists, tuples, dictionaries<br></strong><em>print(&quot;.iloc&quot;)<br>print(df.iloc[0:5,[4]])</em></pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*zJJadgUUvns8HtSYS910mQ.png" /></figure><h3>.Isin()</h3><p>The isin() function comes in handy when you need to check for specific values in a row or columns. One way could be to right multiple == conditions but that could be really tedious. Let&#39;s check an example below.</p><blockquote>CODE</blockquote><pre><strong># select all rows where species is “setosa” or “versicolor”<br></strong>df_new=df.loc[df[‘Species’].isin([‘setosa’,’versicolor’]),:]<br>print(df_new.Species.unique())</pre><blockquote>OUTPUT</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*r5TA9IRHAnSmfQsNi2mXUA.png" /></figure><p>We has successfully filtered all rows with species “setosa” and “versicolor”. Similarly, we can also use isin() to all rows where species is <strong>not</strong> “setosa” or “versicolor”.</p><blockquote><strong>CODE</strong></blockquote><pre><strong># select all rows where species is not “setosa” and “versicolor”<br></strong>df_new=df.loc[~df[‘Species’].isin([‘setosa’,’versicolor’]),:]<br>print(df_new.Species.unique())</pre><blockquote><strong>OUTPUT</strong></blockquote><h3>Modifying a dataframe</h3><h4>Views and Copies</h4><p>Now that we have a good understanding of how to use loc and iloc, lets move on to understanding how to modify a dataframe or create new dataframe by modifying existing one. In order to understand this we need to learn about views and copies in pandas.Till now we have been creating views of a dataframe which is just a subset of the dataframe, when modifying a dataframe we need to be careful of whether we are modifying a view or the original dataframe. Lets check out the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*5oWVimJztSG-xaG7Wn69Ew.png" /><figcaption>Picture courtesy — <a href="https://www.dataquest.io/blog/settingwithcopywarning/">https://www.dataquest.io/blog/settingwithcopywarning/</a></figcaption></figure><p>Let’s try to modify our dataframe with the script below.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#we want to modify row 5 value for column &quot;target&quot;<br></strong>df_copy=df</pre><pre><strong># print rows where sepal length&lt;=4.5 and column target</strong><br>print(“Original value : “,df_copy[df_copy[‘sepal length (cm)’]&lt;=4.5][[‘target’]])</pre><pre><strong># lets modify this value</strong><br>df_copy[df_copy[‘sepal length (cm)’]&lt;=4.5][[‘target’]]=2</pre><pre><strong># lets check if the value has changed</strong><br>print(“Modified value : “,df_copy[df_copy[‘sepal length (cm)’]&lt;=4.5][[‘target’]])</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*OhTmTIJ1JJe99KOWF0gb8Q.png" /></figure><p>The value did not change! And we got this big warning from pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNq2ORNkofRI-aVY6tRIKA.png" /><figcaption>SettingWithCopyWarning</figcaption></figure><p>We get SettingWithCopyWarning as pandas is not sure whether the original dataframe got modified or a view got modified. As we can see the target column with sepal length &lt;= 4.5 does not change. This warning is a way for pandas to let us know that things might not have gone as expected. We can solve this by using .loc or .iloc and not using chaining.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFIQwwlLMc7-83iYHBsl2w.png" /><figcaption>Picture courtesy — <a href="https://www.dataquest.io/blog/settingwithcopywarning/">https://www.dataquest.io/blog/settingwithcopywarning/</a></figcaption></figure><p>Next, let’s see how can we do away with this warning.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#print rows where sepal length&lt;=4.5 and column target<br></strong>print(&quot;Original value : &quot;,df_copy.loc[df_copy[&#39;sepal length (cm)&#39;]&lt;=4.5,[&#39;target&#39;]])</pre><pre><strong>#lets modify this value<br></strong>df_copy.loc[df_copy[&#39;sepal length (cm)&#39;]&lt;=4.5,[&#39;target&#39;]]=2</pre><pre><strong>#lets check if the value has changed<br></strong>print(&quot;Modified value : &quot;,df_copy.loc[df_copy[&#39;sepal length (cm)&#39;]&lt;=4.5,[&#39;target&#39;]])</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*GtJqNx6tECyfcM5ArwIk2g.png" /></figure><p>Voila! The value has changed now. When modifying dataframe we should avoid using chaining [df_copy[&#39;sepal length (cm)&#39;]&lt;=4.5][[&#39;target&#39;]]]and use .loc or .iloc.<strong><em><br></em></strong>Now, let’s try to modify dataframe using .loc.</p><blockquote><strong>CODE</strong></blockquote><pre>df_copy = df</pre><pre><strong>#create a copy of dataframe</strong><br>df_copy_sub= df_copy.loc[df_copy[‘sepal length (cm)’]&lt;=4.5,:]</pre><pre><strong>#original value</strong><br>print(“Original value “, df_copy_sub[‘target’])</pre><pre><strong>#lets modify this value</strong><br>df_copy_sub[‘target’]=3</pre><pre><strong>#lets check if the value has changed</strong><br>print(“Modified value :”,df_copy_sub[‘target’])</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*o42P6nygbG-_dX8AuxrzpA.png" /></figure><p>The SettingWithCopyWarning warning appears again though we have used .loc. This is because df_copy is not a copy of df, so when we try to modify df_copy pandas is again confused. To avoid this, better to use df_copy=df.copy() and not df_copy=df.</p><pre>df_copy=df.copy()<br># save the dataframe<br>df_copy_sub= df_copy.loc[df_copy[&#39;sepal length (cm)&#39;]&lt;=4.5,:].copy()</pre><pre><strong><em>#check original value<br></em></strong>print(df_copy_sub[&#39;target&#39;])</pre><pre><strong><em>#lets modify this value<br></em></strong>df_copy_sub[&#39;target&#39;]=3</pre><pre><strong><em>#lets check if the value has changed<br></em></strong>print(df_copy_sub[&#39;target&#39;]) #it get changed</pre><p>Finally, we got rid of the pesky SettingWithCopyWarning.</p><h4>Appending dataframes</h4><p>It is common to append 2 dataframes on columns or rows while working our way through data and pandas provides a simple way to do so with the concat function.</p><h4>Dataframes can be appended on column by using option axis=1</h4><blockquote><strong>CODE</strong></blockquote><pre><strong>#lets create a copy of existing data frame<br></strong>df_1= df.copy()<br>df_2= df.copy()</pre><pre><strong>#lets append by column<br></strong>df_append_bycol= pd.concat([df_1,df_2],axis=1)<br><strong>#another way to append by column<br></strong>df_append_bycol= pd.concat([df_1,df_2],axis=”columns”)</pre><pre>print(“Original Dataframe — “,df.shape) <br>print(“Appended Dataframe — “,df_append_bycol.shape)</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*2D38dWKwBxFge33ZuZmWhQ.png" /></figure><p>The resulting appended dataframe has double the number of columns as we have simply appended our dataframe to itself. Next, let’s see how to append dataframes on columns when the 2 dataframes that don’t have same dimensions.</p><h4>Unequal Number of Rows</h4><p>Check what happens when 2 dataframes have unequal number of rows. In the example below first dataframe has only 6 rows while the second dataframe has 150 rows. The concatenated dataframe has NaN values in the first 5 columns (coming from first dataframe) in all rows beyond row 6.</p><blockquote><strong>CODE</strong></blockquote><pre>df_1= df.loc[0:5,:].copy() # df_1 has only 6 rows<br>df_2= df.copy()</pre><pre><strong>#lets append by column<br></strong>df_append_bycol= pd.concat([df_1,df_2],axis=1)<br>print(“Original Dataframe — “,df.shape) <br>print(“Appended Dataframe — “,df_append_bycol.shape)</pre><pre><strong>#notice the first 5 columns are NaN from row 7 onwards<br></strong>print(&quot;Concatenated Dataframe&quot;)<br>print(df_append_bycol.head(20))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*pNM18HpLQ7LP5ZYWV8KeXg.png" /></figure><h4>Different Row Index</h4><p>Check what happens when 2 dataframes have different row indexes. In the example below first dataframe has row index 5 to 10 while second dataframe has row index 0 to 149. The concatenated dataframe has NaN values in the first 5 columns (coming from first dataframe) in all rows but rows 5 to 10. What is happening is concat function merges the 2 dataframes on row index, so when concatenating dataframes we need to keep any eye on the row index as well. If you don’t care about the index, this can be changed by resetting index for dataframe.</p><blockquote><strong>CODE</strong></blockquote><pre>df_1= df.loc[5:10,:].copy() # df_1 has only 6 to 10 from original dataframe<br>df_2= df.copy()</pre><pre><strong>#lets append by column<br></strong>df_append_bycol= pd.concat([df_1,df_2],axis=1)<br>print(“Original Dataframe — “,df.shape) <br>print(“Appended Dataframe — “,df_append_bycol.shape)</pre><pre><strong>#notice the first 5 columns are not NaN only for rows 5 to 10<br></strong>print(&quot;Concatenated Dataframe&quot;)<br>print(df_append_bycol.head(20))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDTE0ckX0L2Cfp1yyxfXqg.png" /></figure><blockquote><strong>CODE</strong></blockquote><pre><strong>#reset index<br></strong>df_1= df.loc[5:10,:].copy().reset_index(drop=True) <br>df_2= df.copy()</pre><pre><strong>#lets append by column<br></strong>df_append_bycol= pd.concat([df_1,df_2],axis=1)</pre><pre>print(“Original Dataframe — “,df.shape)<br>print(“Appended Dataframe — “,df_append_bycol.shape)<br>print(“\n”)</pre><pre><strong>#notice the first 5 columns are not NaN for rows 5 to 10 </strong>print(“Concatenated Dataframe with reset index”)<br>print(df_append_bycol.head(20))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L7KE59l1RUxNTYAzBwlLg.png" /></figure><h4>Dataframes can be appended on row by using option axis=0</h4><p>When appending dataframes by row, the row indexes also get appended and need to be reset. Also, the column names should be same in the 2 dataframes, else pandas will treat as different columns.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#lets create a copy of existing data frame “df”<br></strong>df_1= df.loc[0:5,:].copy()<br>df_2= df.loc[0:5,:].copy()</pre><pre><strong>#lets append by row<br></strong>df_append_byrow= pd.concat([df_1,df_2],axis=0) # check the row index<br>print(“\n”)<br>print(“Original Dataframe — “,df.shape)<br>print(“Appended Dataframe — “,df_append_bycol.shape)<br>print(“\n”)<br>print(“Concatenated Dataframe without reset index”)<br>print(df_append_byrow.head(10))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*2VAfc1vkz5MYtdeJ-dyVeQ.png" /></figure><blockquote><strong>CODE</strong></blockquote><pre><strong>#lets append by row and reset index<br></strong>df_append_byrow= pd.concat([df_1,df_2],axis=0).reset_index(drop=True)</pre><pre>print(“\n”)<br>print(“Original Dataframe — “,df_1.shape)<br>print(“Appended Dataframe — “,df_append_byrow.shape)<br>print(“\n”)</pre><pre><strong>#check the row index<br></strong>print(“Concatenated Dataframe with reset index”)<br>print(df_append_byrow.head(10))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*NjxW202inbyB1NErq8RnKg.png" /></figure><h4>Unequal Number of Columns</h4><p>Check what happens when 2 dataframes have unequal number of columns. In the example below first dataframe has only 3 columns while second dataframe has 5 columns. The concatenated dataframe has NaN values in the first 10 rows (coming from first dataframe) in columns that are missing from it.</p><p>Interesting fact! Notice that in the concatenated dataframe the order of columns has changed, concat reorders the columns in alphabetical order, use sort= False to turn this off.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#lets take a smaller subset to be able to inspect the results<br></strong>df_1= df.iloc[0:10,0:1].copy() # df_1 has only 6 rows<br>df_2= df.iloc[0:10,:].copy()</pre><pre>print(df_1.head())<br>print(df_2.head())</pre><pre><strong>#lets append by row<br></strong>df_append_byrow= pd.concat([df_1,df_2],axis=0,sort=False)</pre><pre>print(&quot;\n&quot;)<br>print(“Original Dataframe1 — “,df_1.shape)<br>print(“Original Dataframe2 — “,df_2.shape)</pre><pre>print(&quot;Appended Dataframe - &quot;,df_append_byrow.shape)<br>print(&quot;\n&quot;)<br>print(&quot;Concatenated Dataframe&quot;)<br>print(df_append_byrow.head(20))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*M1fMmuraSiGxoyP4twKY-A.png" /></figure><h4>Handling duplicates</h4><p>It’s one of basic data sanity checks to look for duplicate rows and columns and treat them appropriately before commencing any analysis on data. And you guessed it right, pandas has a nifty function to do this — drop_duplicates(). With this function we can either <strong>drop all duplicates</strong> or <strong>keep the first/last duplicate</strong> (after ordering by some other columns). We can also consider only a subset of columns when searching for duplicates by using subset option. Let’s see how this works.</p><pre><strong><em>#lets first add some duplicate rows to our dataframe<br></em></strong>df_1= df.loc[0:5,:].copy()<br>df_2= df.loc[0:5,:].copy()<br>df_hasduplicates=pd.concat(<br>                [df_1,df_2],axis=0).reset_index(drop=True) <br></pre><p>Our data set with duplicate records is ready, this dataframe should have one duplicate for each record. Now, let’s first drop all duplicates.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#drop them all<br></strong>df_noduplicates= df_hasduplicates.drop_duplicates()<br>print(“Dataframe without duplicates “,df_noduplicates.shape)<br>print(df_noduplicates.head(5))</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*eIYLASZs6eF1jKQsuKdULw.png" /></figure><p>We can see that the dataframe is back to original shape, which means all duplicates have been dropped. Next, we try to drop only those records that have duplicate values in <strong>target</strong> column.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#let’s check how many duplicate values are there in target column<br>#we can check using group by function (will be covered in a later article)</strong><br>print(“Dataframe with duplicates”)<br>print(df_hasduplicates[‘target’].value_counts())<br>print(“\n”)</pre><pre><strong>#drop the rows with duplicate target column</strong><br>df_noduplicates= df_hasduplicates.drop_duplicates(subset=[‘target’])<br><strong># let’s check if target column has duplicates now<br></strong>print(“Dataframe without duplicates “)<br>print(df_noduplicates[‘target’].value_counts())<br>print(“\n”)</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*ASrR4uarW_p9UP-bD2j7hQ.png" /></figure><p>We can see that the dataframe with duplicate values has 8 records with value 0, 2 records with value 1 and 2 records with value 2 and the dataframe without duplicates has 1 value of each type.</p><p>Note, that here pandas keeps the first record for each value of target column. Next, lets try to use the option keep to keep records with lowest sepal length.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#drop the rows with duplicate target column while keeping the row with lowest sepal length<br>#first sort by target and petal length<br></strong>df_hasduplicates.sort_values([‘target’,’sepal length (cm)’],ascending=False,inplace=True)</pre><pre><strong>#drop duplicates<br></strong>df_noduplicates_2= df_hasduplicates.drop_duplicates(subset=[‘target’],keep=’last’)</pre><pre><strong>#let’s check if target column has duplicates now<br></strong>print(“Dataframe without duplicates “)<br>print(df_noduplicates_2[‘target’].value_counts())<br>print(“\n”)</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*2wi3sV7SXirLlvTDHC84Kw.png" /></figure><p>Again, all duplicate values are gone and if you inspect the dataframe this time the lowest values of sepal length have been kept. For first and second values of target column, the lowest values happen to be in the first column by chance, hence the outputs don’t change for these 2 records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*WpeNfY_ofFB640mK5XIkog.png" /></figure><h4>Handling missing values</h4><p>Knowing how to find and replace missing values is key to data analysis. In pandas we can filter out both rows and columns with any or all missing values with the dropna() function. Let&#39;s see the different ways in which pandas lets us manage missing values.</p><p>Firstly, lets introduce some missing values into our data set.</p><pre><strong><em>#import numpy library<br></em></strong>import numpy as np</pre><pre><strong><em>#lets first introduce some missing values into our dataframe<br></em></strong>df_copy = df.copy()<br>print(df_copy.shape)</pre><pre><strong><em>#lets randomly pick some rows and column positions and assign them to NaN<br></em></strong>np.random.seed(200)<br>row=np.random.randint(0,df_copy.shape[0]-1,10)<br>col=np.random.randint(0,df_copy.shape[1]-1,1)<br>print(row,col)<br>df_copy.iloc[row,col]=np.nan</pre><p>Now our data set has missing values. Let’s see how to check for missing values in a dataframe.</p><blockquote><strong>CODE</strong></blockquote><pre><strong># Check how many missing values in total<br></strong>print(“No. of missing values :”,df_copy.isnull().sum().sum())<br>print(“\n”)</pre><pre><strong># Check how many missing values by columns<br></strong>print(“No. of missing values :”)<br>print(df_copy.isnull().sum())</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*kukiwwEeFyPFWkp93O-78A.png" /></figure><p>All right, so we have 5 missing values in our dataset and all of them are in the target column. Next, lets say you want to drop all records with <strong>any missing value. </strong>This is how we can do this using<strong> dropna</strong> function.</p><blockquote><strong><em>CODE</em></strong></blockquote><pre><strong>#Drop rows with any missing values <br></strong>df_nonull=df_copy.dropna(how=’any’)<br>print(df_nonull.isnull().sum())</pre><blockquote><strong><em>OUTPUT</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*SbLqSFaZHw0IwnvtM6KA3Q.png" /></figure><p>As we can see, no missing values anymore, all rows with missing values have been dropped. We can also just drop records where a specific column has missing values. Let’s see how we can do this.</p><pre><strong># Drop rows with missing values in sepal length column<br></strong>df_nonull=df_copy.dropna(subset=[‘sepal length (cm)’],how=’any’)<br>print(df_nonull.isnull().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*Q-vmX7dlQvLqHJif7TYAzg.png" /></figure><p>As column <strong>sepal length </strong>did not have any missing values to begin with, no records are dropped from the dataframe. Try the same with column <strong>target </strong>!</p><p>Now, lets see how we can filter dataframe on columns with no missing values with the <strong>.all() </strong>function. Let’s say you only want to kept columns with no missing values.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#get all columns with no null values<br></strong>df_nonull=df_copy.loc[:,df_copy.notnull().all()]<br>print(df_nonull.isnull().sum()) <br>print(“Columns with no null values:”, df_nonull.columns.values)</pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpdhzjSIYXrF1aZrCzSscw.png" /></figure><p>We can see that these are columns with no missing values. Next, along similar lines, let’s see how we can filter all columns with any non-null values.</p><blockquote><strong>CODE</strong></blockquote><pre><strong>#get all columns with any non-null values<br></strong><em>df_nonull=df_copy.loc[:,df_copy.notnull().any()]<br>print(df_nonull.isnull().sum()) <br>print(“Columns with any non-null values:”, df_nonull.columns.values)</em></pre><blockquote><strong>OUTPUT</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w50Z1B2NHy6Kojikx6mnTg.png" /></figure><p>We can see all columns have some non-null values in this dataframe. Next, let’s see how to get all columns with any missing values.</p><p><strong>CODE</strong></p><pre><strong># get all columns with any non-null values</strong><br>df_nonull=df_copy.loc[:,df_copy.isnull().any()]<br>print(df_nonull.isnull().sum()) <br>print(“Columns with any null values:”, df_nonull.columns.values)</pre><p><strong>OUTPUT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*pO9cuHl-0yIWQYZ6S2qL4Q.png" /></figure><p>As expected, “target” is the only column with null values. So, we saw quiet a few ways to work with missing values here, but note, these only cover how to identify missing values, ways to impute missing values will be covered in a later article.</p><h4>Changing datatypes</h4><p>In pandas the most commonly used datatypes are integer, float, object, category and datetime. We can get the data types of all columns in any dataframe by using the .dtypes function. It&#39;s quite common for data to get read in format not appropriate for analysis (especially when reading from sql database) and needs to be changed to appropriate data type before analysis. For converting to numeric we can use astype() function or to_numeric() function which comes in handy especially when you have missing values. There are situations where we just need to select columns of a certain datatype to perform analysis, pandas has a very useful function select_dtypes() to do so as well. Let&#39;s learn with examples.</p><ol><li>Check data types in a dataframe.</li></ol><p><strong>CODE</strong></p><pre><strong><em>#check datatypes in our dataframe<br></em></strong>print(df.dtypes)</pre><p><strong>OUTPUT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*P3Ez_u8QlBX9i7T8zLDxWQ.png" /></figure><p>2. Select all columns of a specific type.</p><p><strong>CODE</strong></p><pre><strong>#lets select all float columns<br></strong>df_float = df.select_dtypes(include=’float64&#39;)<br>print(df_float.dtypes)</pre><p><strong>OUTPUT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*uCOv_iaDTuLhvmuvSEjVSQ.png" /></figure><p>3. Change column type, notice data type of “target” column after conversion.</p><p><strong>CODE</strong></p><pre><strong>#lets convert target column to float type<br></strong>df[‘target’]=df[‘target’].astype(‘float64’)<br>print(df.dtypes)</pre><p><strong>OUTPUT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*8S2GiKk-01kUuvQgjDW-pA.png" /></figure><p>4. Converting data type when missing values are present.</p><p>Pandas does not allow for missing values when converting to integer type and throws error, so if a column has missing values then we can either convert to float or first impute missing value and then convert to integer.</p><pre><strong>#lets introduce some missing values in target column<br></strong>row=np.random.randint(0,df.shape[0],5)<br>df_copy=df.copy()<br>df_copy.loc[row,’target’]=np.nan</pre><pre><strong>#check for missing values<br></strong>print(“Missing values :”,df_copy[‘target’].isnull().sum())</pre><pre><strong>#lets convert target column to int type using astype()<br></strong>df_copy[‘target’]=df_copy[‘target’].astype(int)</pre><pre><strong>#you get an ERROR !!</strong></pre><pre><strong>#now try this<br></strong>df_copy[‘target’]=pd.to_numeric(df_copy[‘target’],errors=’coerce’)<br>print(df_copy.dtypes)</pre><pre><strong>#or this<br></strong>df_copy[‘target’]=df_copy[‘target’].astype(float)</pre><pre><strong>#no ERROR !!</strong></pre><p>That’s all for this tutorial. I hope you find it useful and thanks for reading ! Here’s the notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19c8d1b1c6a0b1ef8e3bdd510a104177/href">https://medium.com/media/19c8d1b1c6a0b1ef8e3bdd510a104177/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ebacf682678" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/practical-pandas-part-2-9ebacf682678">Practical Pandas  — Part 2</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Pandas]]></title>
            <link>https://gangulym23.medium.com/practical-pandas-50586fe90cf8?source=rss-36a67a2be67------2</link>
            <guid isPermaLink="false">https://medium.com/p/50586fe90cf8</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-manipulation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Madhura Ganguly]]></dc:creator>
            <pubDate>Sun, 21 Jul 2019 02:08:36 GMT</pubDate>
            <atom:updated>2019-09-20T06:05:12.312Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginners Guide to Pandas Basics</h3><h4><strong>Quick tutorial to get started with pandas</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnkloJpNwX-mA94lkC9JDg.jpeg" /></figure><p>This is the first article in a series on learning practical applications of Pandas package without getting overwhelmed by too many functions. This is meant for those who are new to pandas and want to learn the how to perform the most common data analysis tasks quickly. Hence, this series is going to cover the details needed to launch your pandas learning without going over everything that’s possible.</p><p>The Jupyter notebook can be accessed from <a href="https://github.com/maddyg/Practical-Pandas-Learning/blob/master/Practical%20Pandas%20-%20Part%201.ipynb">GitHub</a> and also available at the end of this tutorial. I would encourage you to download the Jupyter notebook and follow along by running the script for maximum retention.</p><p>This tutorial covers</p><ol><li>Creating dataframes from numpy arrays</li><li>Creating dataframes by reading files (.csv, .txt,..)</li><li>Creating dataframes from scratch using dictionaries</li><li>Add new column to dataframe</li><li>Recode existing column in dataframe</li><li>Drop column from dataframe</li></ol><h3>Import Packages</h3><p>First, we import <strong>pandas library</strong> and <strong>datasets</strong> module from <strong>sklearn</strong> package to get the data set for this tutorial.</p><pre>import pandas as pd<br>from sklearn import datasets</pre><h3>Load Data Set</h3><p>Load <strong>iris data</strong> set from <strong>datasets</strong> module that was imported. Iris is a famous data set in the world of statistics and has been used for numerous tutorials.</p><p>If you run print(iris) you will see that it returns a dictionary where the first key, value pair is <strong>&quot;data&quot;</strong> and a 150 x 4 numpy array. The second key, value pair is <strong>&quot;target&quot;</strong> and list of integer values. The last key, value pair is<strong> &quot;feature_names&quot;</strong> and a list of names. We shall be using these 3 components to build our <strong>pandas dataframe</strong> that will be used in the rest of this tutorial.</p><pre><strong><em># import some data to play with<br></em></strong>iris = datasets.load_iris()<br>#print(iris)</pre><pre>print(“Iris data shape :”, iris[‘data’].shape)<br>print(‘\n’)</pre><h3>Create DataFrame</h3><p><strong>DataFrames </strong>are most useful data structures in python, they are 2 -dimensional tabular data structures with column names, row names or index and data. We use function DataFrame() to convert the numpy array into a pandas dataframe. This is the only function to create a dataframe in pandas. We can check the columns created with the .columns() function.</p><pre><strong><em># Create data frame<br></em></strong>df=pd.DataFrame(iris.data,columns=iris.feature_names)</pre><pre>print(df.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ue1L4hyPpZai39fg7RsrdQ.png" /><figcaption>Column names</figcaption></figure><h3><strong>Add new column</strong></h3><p>Next we see how a new column <strong>“target”</strong> can be added to an existing dataframe. A new column can be created by assigning a list. This is one of many ways, but this is the most common way of doing this. Learn about other ways in this <a href="https://www.geeksforgeeks.org/adding-new-column-to-existing-dataframe-in-pandas/"><strong>excellent article</strong></a>.</p><pre><strong><em># Lets add another column to the data set<br></em></strong>df[‘target’]=iris[‘target’]</pre><pre>print(“Checking top records: “)<br>print(df.head())<br>print(‘\n’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bf9oX83tLk9oPdAFodb8pg.png" /><figcaption>Column target is added to dataframe</figcaption></figure><h3>Re-code column</h3><pre><strong><em># Create species mapping dictionary<br></em></strong>species_mapping={0:iris[‘target_names’][0],1:iris[‘target_names’][1],2:iris[‘target_names’][2]}<br>print(‘Checking species mapping: ‘)<br>print(species_mapping)<br>print(‘\n’)</pre><pre><strong><em># Use map to recode column<br></em></strong>df[‘Species’] = df[‘target’].map(species_mapping)<br>print(“Checking if Species is created : “)<br>print(df.head())<br>print(‘\n’)</pre><pre><strong><em># Use .replace to recode column<br></em></strong>df[‘Species_2’] = df[‘target’].replace(species_mapping)<br>print(“Checking if Species_2 is created : “)<br>print(df.head())<br>print(‘\n’)</pre><h3>Drop columns</h3><p>Columns can be <strong>dropped </strong>by using the .drop() function with option axis=1 specifying that we want to drop a column. Checking the column names again shows that <strong>&quot;Species_2&quot;</strong> has been dropped. We can use tolist() function to convert column names from series to list. This is not necessary but just nicer to look at.</p><pre><strong><em># Drop Species_2</em></strong></pre><pre>df.drop([‘Species_2’],axis=1,inplace=True)<br>print(“Checking if Species_2 is dropped : “)<br>print(df.columns.tolist())<br>print(‘\n’)</pre><h3>Read Data Set</h3><p>Here we have loaded the iris data set from <strong>datasets</strong> module of <strong>sklearn</strong> package so that anyone can run the script. But in actual work scenario you would need to read in the data set either from a server or from your local folder. Keeping that in mind lets see how it would work if you have the same file stored in a local folder. For this we shall first write out the dataframe created above and then read it back. This way its reproducible for everyone.</p><p>Notice when we write out the dataframe with .to_csv() we specify option index=False, if this is not done an unnamed column with row indexes will be created in the written out file. You can try to write out without this option.</p><p>The most common way to read files with Pandas is with read_csv() function. This function has many parameters that can be used to specify how data needs to be read. For example, by default the first row of the data will be considered to be the header and used to create column names, if the file does not have any headers then specify headers=None, unless we specify column names with option names the dataframe will have unnamed columns.Take a look at pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html">documentation</a> to learn more about the available options when reading in data.</p><pre><strong><em># Write out file<br></em></strong>df.to_csv(‘Iris.csv’,index=False)</pre><pre><strong><em># Read back file<br></em></strong>iris_df = pd.read_csv(‘Iris.csv’)<br>print(iris_df.head())</pre><h3>Create DataFrame from scratch</h3><p>Though not needed that often it is useful to know how to create a pandas dataframe from scratch. We can create a dataframe from a dictionary with values as lists, where dictionary keys are the dataframe column names and the values are column values. There are options to specify datatypes and index values. Take a look at pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html">documentation</a> to learn more</p><pre><strong><em># create dictionary<br></em></strong>dat_dict = {‘Name’:[‘El’,’Mike’,’Dustin’,’Lucas’,’Max’,’Will’],’Gender’:[‘Girl’,’Boy’,’Boy’,’Boy’,’Girl’,’Boy’]}<br># convert to dataframe<br>dat_df = pd.DataFrame(dat_dict)</pre><pre><strong><em># check output<br></em></strong>print(dat_df.head())</pre><h3>Inspecting a DataFrame</h3><p>Now that we have learnt how to create a pandas dataframe be it from an existing loaded data set or reading in an external file or from scratch, lets inspect some properties of a dataframe. type() function returns the class type of<strong> &quot;dat_df&quot; </strong>as pandas dataframe and that of column <strong>&quot;Name&quot; </strong>as pandas series. We have not introduced series so far, series are another type of data structure in pandas, they are one dimensional arrays with labels. Each column of a dataframe is a series as you can see from running print(type(dat_df[&#39;Name&#39;])). You can create a series from a numpy array in same way as a dataframe from a dictionary just by replacing .DataFrame() function with .series(). Finally we can insert a series as a new column into a dataframe.</p><pre><strong><em># Check class type<br></em></strong>print(‘Dataframe class :’, type(dat_df))<br>print(‘Dataframe column class :’, type(dat_df[‘Name’]))</pre><pre><strong><em># import numpy library<br></em></strong>import numpy as np</pre><pre><strong><em># create numpy array<br></em></strong>Sibling = np.array([None,’Nancy’,None,’Erika’,’Billy’,’Jonathan’])</pre><pre><strong><em># convert to pandas series</em></strong><br>Sibling = pd.Series(Sibling)<br>print(‘Series :’,Sibling)</pre><pre><strong><em># insert series as new column into dataframe</em></strong><br>dat_df[‘Sibling’]=Sibling<br>print(“New dataframe :”)<br>print(dat_df.head())</pre><p>Here is the ipython notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3763d655082d447dded55c484a6bd887/href">https://medium.com/media/3763d655082d447dded55c484a6bd887/href</a></iframe><p>That’s all for this tutorial. To summarize we have covered how to read and write out data, create pandas dataframe from .csv file, numpy array and dictionary, add new column to dataframe using lists and series, recode existing column in dataframe and drop column from dataframe. The next tutorial will cover more details around data manipulations using pandas. Feed back is welcome :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50586fe90cf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>