<?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 Thanmai Chandaka on Medium]]></title>
        <description><![CDATA[Stories by Thanmai Chandaka on Medium]]></description>
        <link>https://medium.com/@thanmai.chandaka?source=rss-297e54599a81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U2QyxwE3MtXfZluAalzsnw.jpeg</url>
            <title>Stories by Thanmai Chandaka on Medium</title>
            <link>https://medium.com/@thanmai.chandaka?source=rss-297e54599a81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:07:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thanmai.chandaka/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[Creating a Table Maintenance Generator in SAP ABAP: Your Path to Seamless Data Maintenance]]></title>
            <link>https://medium.com/@thanmai.chandaka/creating-a-table-maintenance-generator-in-sap-abap-your-path-to-seamless-data-maintenance-fe63bf945d2e?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe63bf945d2e</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 11:32:53 GMT</pubDate>
            <atom:updated>2023-06-14T11:32:53.724Z</atom:updated>
            <content:encoded><![CDATA[<p>In SAP, a table maintenance generator is a tool used to create a user interface for maintaining data in database tables. It allows users to perform basic operations such as creating, modifying, and deleting records in a table without the need for programming skills.</p><figure><img alt="Table Maintenance Generator in SAP ABAP" src="https://cdn-images-1.medium.com/max/1024/0*JF4ro9LXNL8ujguP" /></figure><p>The table maintenance generator is typically used for custom tables created in SAP, where you want to provide an easy-to-use interface for end users to maintain the data. It generates a set of screens that enable users to view and edit table records.</p><p>Here are the steps to create a table maintenance generator in SAP:</p><p>Step 1. Go to transaction SE11 and enter the table name for which you want to create the maintenance generator.</p><figure><img alt="SAP ABAP Data Dictionary Initial Screen" src="https://cdn-images-1.medium.com/max/790/1*FQHyyFa4r-qfSKku-lAjQA.png" /></figure><p>Step 2. Click on the Display button to view the table details.</p><figure><img alt="Table Display Screen in SAP ABAP DDIC" src="https://cdn-images-1.medium.com/max/917/1*mk8YeTYp3alBzLsjwLVZ3Q.png" /></figure><p>Step 3. From the menu, select “Utilities” and then “Table maintenance generator.”</p><p>Step 4. Enter Authorization Group as &amp;NC&amp;.</p><p>Access to the tables can be restricted through the “Authorization Group”.</p><p>“&amp;NC&amp;” is a default “Authorization Group”.</p><p>Give the “Function group” name as the table name.</p><p>Select Maintenance type One Step.</p><figure><img alt="Table Maintenance Generator Environment in SAP ABAP DDIC" src="https://cdn-images-1.medium.com/max/1024/1*xrwbyHirPHZJbELIoxd3Lg.png" /></figure><p>Step 5. Click on Find Screen Number. Select Propose screen number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhXAy3tocRitQpVvvaJQlg.png" /></figure><p>Step 6. Click on Create button. Once you have made the desired modifications, save and activate the maintenance generator.</p><p>Once you are done with creating, you will get the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*ngOSNLtdYNmv34SxA9HlvQ.png" /></figure><p>Step 7: Once you are done with creating the table maintenance generator, you can create the entries in the table.</p><p>Step 8: Open the table in se11 -&gt; Utilities -&gt; Table Contents -&gt; Create Entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*UDjDBQQBABPGRtLTc2VxPQ.png" /></figure><p>Step 9: Click on “New Entries”.</p><figure><img alt="Table Maintenance Generator" src="https://cdn-images-1.medium.com/max/927/1*VxCDkfpr8pwScFqkqbo4Jw.png" /></figure><p>After creating the table maintenance generator, users can access it through transaction SM30, where they can select the table and perform maintenance operations on the data.</p><p>What is Maintenance Type in Table Maintenance Generator?</p><p>Here you can see there are two types.</p><p>One Step and Two Step</p><p>If we select One-step then only an overview screen is created.</p><p>If we select Two-Step then an overview screen and a single screen are created.</p><p><strong>In One-Step: </strong>While Creating entries only the overview screen will be displayed.</p><p><strong>In Two-Step: </strong>While Creating entries overview screen and the single screen will be displayed.</p><p>It’s important to note that a table maintenance generator is a basic tool for simple data maintenance. If you require more complex functionality or business logic, you may need to develop a custom transaction using ABAP programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe63bf945d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAP ABAP Database Table Creation: A Beginner’s Step-By-Step Guide]]></title>
            <link>https://medium.com/@thanmai.chandaka/a-step-by-step-guide-to-creating-database-tables-in-sap-abap-a4e904591aa8?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4e904591aa8</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 10:47:26 GMT</pubDate>
            <atom:updated>2023-06-14T11:45:39.964Z</atom:updated>
            <content:encoded><![CDATA[<p>In SAP ABAP, creating tables is an essential skill for developers and administrators. Tables provide a structured way to store and manage data within the SAP system. This step-by-step guide will walk you through the process of creating tables in SAP ABAP, ensuring that you understand the necessary steps and techniques involved.</p><figure><img alt="A Step-By-Step Guide to Creating Database Tables in SAP ABAP" src="https://cdn-images-1.medium.com/max/1024/0*4EmmwhLbs0CxWW67" /></figure><p><strong>Database Tables: </strong>Tables are used to store data in a structured format. In the Data Dictionary, you can define tables, and specify fields, data types, lengths, and other properties. Tables can also have foreign key relationships, indexes, and check constraints.</p><p><strong>Data Elements: </strong>Data elements represent the domain-specific description of a table field. They define the semantic attributes of a field, such as the data type, length, and formatting information. Data elements are reusable and can be assigned to multiple fields across different tables.</p><p><strong>Domains: </strong>Domains define the technical attributes of a data element, such as the data type, length, and input checks. They represent the lowest level of data definition and can be used to create data elements and specify field properties.</p><p>To create a database table in SAP ABAP, you can follow these steps:</p><ol><li>Open the ABAP Development Tools (ADT) in the SAP NetWeaver Developer Studio or the corresponding ABAP development environment.</li></ol><figure><img alt="SAP Easy Access Screen" src="https://cdn-images-1.medium.com/max/1024/1*UKRgeWOQQu1k0hUF_8UVoA.png" /></figure><p>2. Create a new ABAP dictionary object by navigating to the ABAP Dictionary transaction (SE11). Enter the table name &amp; choose the option to create a new table (Database table).</p><figure><img alt="SAP ABAP Data Dictionary Initial Screen" src="https://cdn-images-1.medium.com/max/973/1*ixSvu_Mg4zLeGpDAsSqkGQ.png" /></figure><p>3. Provide a descriptive name for the table.</p><p>Define the table’s technical settings, such as the table category and delivery class.</p><figure><img alt="DDIC Delivery &amp; Maintenance" src="https://cdn-images-1.medium.com/max/1024/1*ICImSUsmSt5muZa4TY913w.png" /></figure><p>4. Go to the “Fields” tab and start entering Fields and Data Element names.</p><figure><img alt="DDIC Empty Table" src="https://cdn-images-1.medium.com/max/1024/1*k3Q0-09nH3eLUrrd0bf5Lg.png" /></figure><p>5. First enter the client number field (MANDT), and select the check boxes (Key, Initial Value). Also, enter the standard data element into the client number field (MANDT) and press enter.</p><p><em>&lt;&lt;Note: Even though we don’t check the initial value check box, the system will provide initial values by default in case of null entries.&gt;&gt;</em></p><figure><img alt="Client Number Field SAP ABAP" src="https://cdn-images-1.medium.com/max/1024/1*MWJLWmxz1fW20zdmO2uzLA.png" /></figure><p>Step 6. Now, enter the first field name (STD_ID).</p><p>If it is a key value, check the “Key” checkbox.</p><p>Create “Data Element” of this field, it should start with “Z” (ZSTD_ID).</p><p>Double-click on the “Data Element” to create a domain, and select the yes icon on the below pop-up window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*MY8ssMCCBNdc6OkGF4LmWQ.png" /></figure><p>Then save the package as “Local Object” in the below pop-up.</p><figure><img alt="Local Object SAP ABAP" src="https://cdn-images-1.medium.com/max/792/1*sG17IJlALS17aWdRyX4MuA.png" /></figure><p>Now enter the “Short Description” and “Domain” in the below screen and double-click on that particular domain name.</p><figure><img alt="DOmain, Data Type SAP ABAP" src="https://cdn-images-1.medium.com/max/940/1*2Af_JeGovZps6DWeb3wo1Q.png" /></figure><p>Now you can see the below screen, here you can define Data type, No. of chars, Decimal Places, and enter.</p><figure><img alt="Domain in SAP ABAP" src="https://cdn-images-1.medium.com/max/940/1*jDVma_ty8QUYojjzOoZmzg.png" /></figure><p>The system will automatically take the output length. If you want you can check the “Lowercase” option.</p><p>If you want to specify some more properties you can go to the “Value Range” tab and define some Fixed Values, Intervals like Lower limit, Upper limit.</p><p>Once you are done specifying the properties, click on the “Activate” button and activate the domain.</p><p>Now go back and open the “Field Label” tab and fill in the field labels of all lengths and enter. The length will automatically be filled by the system once you click enter.</p><figure><img alt="Field Label, Data Element in SAP ABAP" src="https://cdn-images-1.medium.com/max/940/1*aHf_kUGHZ-BNX9VTfkeC6w.png" /></figure><p>Now save and activate.</p><p>8. Repeat step 7 for each field you want to add to the table.</p><p>9. Save your changes.</p><figure><img alt="Database Table in SAP ABAP" src="https://cdn-images-1.medium.com/max/940/1*tHOfxj8T51SSTCB1zVu91w.png" /></figure><p>10. If necessary, assign a primary key to the table by selecting the Keys option in the menu and defining the primary key fields.</p><p>11. Open technical settings and fill the required fields like “Data Class” &amp; “Size Category”.</p><figure><img alt="Technical Settings in SAP ABAP" src="https://cdn-images-1.medium.com/max/940/1*xpWK6ydeqMWXGlIyDDtmDg.png" /></figure><p>12. Save and activate the table.</p><p>13. Your database table is now created in SAP ABAP.</p><p>14. To create entries in the DB Table, In the header menu Click on Utilities -&gt; Table Contents -&gt; Create Entries.</p><figure><img alt="Creating Table Entries in SAP ABAP" src="https://cdn-images-1.medium.com/max/940/1*GI2-1nstraKIoOHoZNujdA.png" /></figure><p>Enter the values, save the entries, and then create new entries.</p><p>15. If you want to see the entries of the table, then go back to the fields and click on the “Contents” button.</p><figure><img alt="Contents Button in SAP ABAP" src="https://cdn-images-1.medium.com/max/22/1*NZkveHLQ67NVVhT37GNtDg.png" /><figcaption>Contents Button</figcaption></figure><p>16. Here, either you can enter these from and to limits or you can directly click on the “Execute” button.</p><figure><img alt="EXEcute Button in SAP ABAP" src="https://cdn-images-1.medium.com/max/31/1*Vs-hFAXSfaMpbbcHV9f2kA.png" /><figcaption>Execute Button</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*CWh9BfBkG-wMwBu5MabUIQ.png" /></figure><p>It is important to note that the exact steps and terminology may vary slightly depending on the version of SAP you are using and the specific development environment you are working with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4e904591aa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression]]></title>
            <link>https://medium.com/@thanmai.chandaka/logistic-regression-7fca5a80f6ff?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fca5a80f6ff</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 11:08:57 GMT</pubDate>
            <atom:updated>2022-11-13T11:08:57.145Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, you will learn about the Logistic Regression algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*d-oMY6jWkCxS8JLO.png" /></figure><p>Logistic regression is one of the most popular Machine Learning algorithms, which comes under the Supervised Learning technique. It is used for predicting the categorical dependent variable using a given set of independent variables.</p><p>Logistic regression is a statistical technique used to predict a categorical dependent variable based on one or more independent variables. In logistic regression, the dependent variable is binary or dichotomous, i.e. it can take only two values, 0 and 1.</p><p>Logistic Regression is much similar to Linear Regression except that how they are used. Linear Regression is used for solving Regression problems, whereas Logistic regression is used for solving the classification problems. In Logistic regression, instead of fitting a regression line, we fit an “S” shaped logistic function, which predicts two maximum values (0 or 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K22mHYUOizCm9L2f.jpeg" /></figure><p>Logistic Regression is a significant machine learning algorithm because it can provide probabilities and classify new data using continuous and discrete datasets. It can be used to classify the observations using different types of data and can easily determine the most effective variables used for the classification.</p><p>Mathematically, a logistic regression model is represented as:</p><p>y = β0 + β1X1 + β2X2 + … + βnXn —-(I)</p><p>where,</p><p>y is the probability of a given variable x belonging to a certain class.</p><p>β0 is the intercept.</p><p>β1, β2, …, βn are the coefficients of the independent variables X1, X2, …, Xn.</p><p>X1, X2, …, Xn are the independent variables.</p><p>But, when we use equation(I) to calculate probability, we would get values less than 0 as well as greater than 1. That doesn’t make any sense. So, we need to use such an equation that always gives values between 0 and 1, as we desire while calculating the probability.</p><p><strong>Sigmoid Function:</strong></p><p>We use the sigmoid function as the underlying function in Logistic regression. Mathematically and graphically, it is shown as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gv3g7DEwIsHI5QZ_.png" /><figcaption>Sigmoid Function</figcaption></figure><p>The sigmoid function is used in logistic regression to map the input values (x) to output values (y) between 0 and 1. This is done by squashing the input values using the sigmoid function so that they are constrained between 0 and 1. This output can then be interpreted as a probability, which is useful for classification tasks.</p><p>Although there are other functions as well, which can be used, sigmoid is the most common function used for logistic regression.</p><p>The logistic function is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*4bV5L08gIyrmhy-Y" /></figure><p><strong>Cost Function:</strong></p><p>The cost function is used to optimize the parameters of the logistic regression model. It is a measure of how well the model is able to predict the correct output values (y) given the input values (x). The cost function is minimized during training so that the model can learn the optimal parameters for mapping the inputs to the outputs.</p><p>In the case of Linear Regression, the Cost function is –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*pvAwCdoIUbnWSSNWMXpdJg.png" /></figure><p>But for Logistic Regression,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*zswVdENgJYNaI-p5WAR2Ug.png" /></figure><p>It will result in a non-convex cost function. But this results in cost function with local optima’s which is a very big problem for Gradient Descent to compute the global optima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YEYgMQNrqsQd5Rok.png" /></figure><p>Logistic Regression returns the non-convex function. For that we need to change the cost function, we have to use Log Loss Cost FUnction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*k_zAYADF2yFNKOWt.png" /></figure><p>Cost = 0 if y = 1, hθ(x) = 1<br>But as<br>hθ(x) -&gt; 0 then, Cost -&gt; Infinity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*YD2EgUc8OfK2_TrOcdsnsA.png" /></figure><p>To fit parameter <strong>θ</strong>, J(θ) has to be minimized and for that Gradient Descent is required.</p><p>Gradient Descent looks similar to that of Linear Regression but the difference lies in the hypothesis hθ(x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*7Hk99GVgJB01ZFiy_m0L1g.png" /></figure><p><strong>Evaluation Metrics for Classification Problem:</strong></p><p>In machine learning, once we have a result of the classification problem, how do we measure how accurate our classification is? For a regression problem, we have different metrics like R Squared score, Mean Squared Error etc. what are the metrics to measure the credibility of a classification model?</p><p>Metrics In a regression problem, the accuracy is generally measured in terms of the difference in the actual values and the predicted values. In a classification problem, the credibility of the model is measured using the confusion matrix generated, i.e., how accurately the true positives and true negatives were predicted. The different metrics used for this purpose are:</p><p>Accuracy<br>Recall<br>Precision<br>F1 Score<br>AUC( Area Under the Curve)<br>RUC(Receiver Operator Characteristic)</p><p><strong>Confusion Matrix: </strong>A typical confusion matrix looks like the figure shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*JzyzW_CPd_whmZw_.png" /></figure><p>Where the terms have the meaning:</p><p>True Positive(TP):__ A result that was predicted as positive by the classification model and also is positive</p><p>True Negative(TN):__ A result that was predicted as negative by the classification model and also is negative</p><p>False Positive(FP):__ A result that was predicted as positive by the classification model but actually is negative</p><p>False Negative(FN):__ A result that was predicted as negative by the classification model but actually is positive.</p><p>The Credibility of the model is based on how many correct predictions did the model do.</p><p><strong>Accuracy: </strong>Accuracy is the most intuitive performance measure and it is simply a ratio of correctly predicted observation to the total observations. One may think that, if we have high accuracy then our model is best. Yes, accuracy is a great measure but only when you have symmetric datasets where values of false positive and false negatives are almost same. Therefore, you have to look at other parameters to evaluate the performance of your model. For our model, we have got 0.803 which means our model is approx. 80% accurate.</p><p>Accuracy = TP+TN/TP+FP+FN+TN</p><p><strong>Precision : </strong>Precision is the ratio of correctly predicted positive observations to the total predicted positive observations. The question that this metric answer is of all passengers that labeled as survived, how many actually survived? High precision relates to the low false positive rate. We have got 0.788 precision which is pretty good.</p><p>Precision = TP/TP+FP</p><p><strong>Recall (Sensitivity) : </strong>Recall is the ratio of correctly predicted positive observations to the all observations in actual class — yes. The question recall answers is: Of all the passengers that truly survived, how many did we label? We have got recall of 0.631 which is good for this model as it’s above 0.5.</p><p>Recall = TP/TP+FN</p><p><strong>F1 score</strong> : F1 Score is the weighted average of Precision and Recall. Therefore, this score takes both false positives and false negatives into account. Intuitively it is not as easy to understand as accuracy, but F1 is usually more useful than accuracy, especially if you have an uneven class distribution. Accuracy works best if false positives and false negatives have similar cost. If the cost of false positives and false negatives are very different, it’s better to look at both Precision and Recall. In our case, F1 score is 0.701.</p><p>F1 Score = 2*(Recall * Precision) / (Recall + Precision)</p><p><strong>ROC(Receiver Operator Characteristic):</strong> We know that the classification algorithms work on the concept of probability of occurrence of the possible outcomes. A probability value lies between 0 and 1. Zero means that there is no probability of occurrence and one means that the occurrence is certain.</p><p>But while working with real-time data, it has been observed that we seldom get a perfect 0 or 1 value. Instead of that, we get different decimal values lying between 0 and 1. Now the question is if we are not getting binary probability values how are we actually determining the class in our classification problem?</p><p>There comes the concept of Threshold. A threshold is set, any probability value below the threshold is a negative outcome, and anything more than the threshold is a favourable or the positive outcome. For Example, if the threshold is 0.5, any probability value below 0.5 means a negative or an unfavourable outcome and any value above 0.5 indicates a positive or favourable outcome.</p><p>Now, the question is, what should be an ideal threshold?</p><p>The following diagram shows a typical logistic regression curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*lrulEMqXm0RbGcIDKSKupQ.png" /></figure><p>The horizontal lines represent the various values of thresholds ranging from 0 to 1.<br>Let’s suppose our classification problem was to identify the obese people from the given data.<br>The green markers represent obese people and the red markers represent the non-obese people.<br>Our confusion matrix will depend on the value of the threshold chosen by us.<br>For Example, if 0.25 is the threshold then<br> TP(actually obese)=3<br> TN(Not obese)=2<br> FP(Not obese but predicted obese)=2(the two red squares above the 0.25 line)<br> FN(Obese but predicted as not obese )=1(Green circle below 0.25line )</p><p><strong>AUC(Area Under Curve):</strong> It helps us to choose the best model amongst the models for which we have plotted the ROC curves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*L07lMR01LpBKJRNYzQVe5g.png" /></figure><p>The best model is the one which encompasses the maximum area under it.<br>In the adjacent diagram, amongst the two curves, the model that resulted in the red one should be chosen as it clearly covers more area than the blue one</p><p><strong>Conclusion: </strong>For the practical implementation of Logistic Regression, please visit my <a href="https://github.com/Thanmai3249/Logistic-Regression">GitHub</a>.</p><p><strong>Closing Remarks: </strong>Please let me know if you have any questions in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fca5a80f6ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regularization: Ridge, Lasso, Elastic Net Regression]]></title>
            <link>https://medium.com/@thanmai.chandaka/regularization-ridge-lasso-elastic-net-regression-d89c1a893e1d?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/d89c1a893e1d</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 14:56:26 GMT</pubDate>
            <atom:updated>2022-10-19T14:56:26.340Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will learn about Ridge, Lasso, Elastic Net Regrssion algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VizZ-0o0QrXu2iG8.png" /></figure><p><strong>Bias &amp; Variance:</strong></p><p>Bias occurs when the model makes assumptions during training but these assumptions are not be correct when the model applies to testing data. these assumptions by the model to make the target function easier to learn. On the other hand, variance is the sensitivity of the model towards changes in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*bokj57M-GiZDdRBr.png" /></figure><p>However, variance is when the model memorizes or learns too much from the training data, which hinders its ability to generalize leading to inaccurate predictions when introduced to testing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*dwZPJmuinfWIJNI1.jpg" /></figure><p>By analyzing the bias-variance, it is possible to evaluate the performance of a model. An accurate model will have low variance and low bias. High bias is when the model fails to take-in the relation between the features and target, which leads to inaccurate predictions, this is called underfitting. When the complexity of the model increases, the variance increases as well. high variance causes the spread of data, which is also refer overfitting.</p><p>The ordinary least squares model performs poorly on a large multivariate dataset which has more variables than samples. To prevent overfitting, we take a penalty approach called regularization, to improve the performance of the model, by restricting the model.</p><p><strong>Ridge Regression (L2 Regularization):</strong></p><p>The advantage of using the ridge regression is to avoid overfitting. it works in the same way as the linear regression but it just adds an extra term (α) which helps in the reduction of overfitting. the goal of any machine learning model is to generalize the pattern which it needs to be predicted; i.e. the model should work best on both training as well as test data. overfitting occurs when the trained model performs well on the training data and performs poorly on the testing dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*9y4ojNYQZoEnTI_z" /></figure><p>The influence of the penalty term is control by the alpha parameter. the alpha parameter decides the severity of the penalty imposed on the model. Higher alpha increases regularization and leads to less complex models. when =0, the result is similar to the least-squares method. As , the penalty increases and the coefficents move towards zero, however, they will never reach zero. It is also important to know that after a point, higher alpha values, might lead to underfitting. cross-validation is a great way to find the appropriate value of alpha.</p><p>In simpler terms, if ridge regression finds two models that perform equally well on training data, it will prefer the model which has a smaller sum of model coefficients. ridge regression provides with better grouping effect, in which colinear features are select up together.</p><p><strong>Lasso Regression (L1 Regularization):</strong></p><p>Lasso regression is another form of regularized linear regression, similar to ridge regression with a difference in the penalty parameter. Thus, this regression uses the l1 penalty i.e minimizes the sum of the absolute values of model coefficients. The penalty parameter in lasso regression sets the model coefficients to zero for features with less prediction power.</p><p>This effect allows for improved feature selection by eliminating less influential features. As a result, it is usually used on datasets having more number of features. The function of the alpha parameter is similar to that in ridge regression. The cost function for lasso regression is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/0*7GfXQlHS-fw_b3JS" /></figure><p><strong>Elastic Net Regression:</strong></p><p>We can choose ridge and lasso regression when we have enough information about the features but it is difficult to choose one when the data has too many features and variables. In such cases, we use elastic-net regression which is good at estimating correlations between features. The penalty function of elastic net regression is a combination of both l1 and l2 penalties from lasso and ridge regression respectively. In other words, it combines the power of both ridge and lasso regression. The cost function for elastic-net regression is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*7MFGdi89M2KISNn7" /></figure><p>The elastic net regression has the basic least-squares followed by lasso and ridge penalties with their respective alpha parameters 1and 2. The most optimum combination of alpha parameters can be determined using cross-validation.</p><p><strong>Conclusion: </strong>In order to make accurate predictions, linear regression attempts to map the relationship between the target and the features. High bias and high variance, however, impair accuracy. We use regularized variations of the ols, ridge, lasso, and elastic net regression to address this issue and enhance model performance.</p><p><strong>Closing Remarks: </strong>Please let me know if you have any questions in the comments section.</p><p>Please check my previous blogs on <a href="https://medium.com/@thanmai.chandaka/lists-in-python-a01879e7f237">Lists in Python</a>, <a href="https://medium.com/@thanmai.chandaka/tuples-in-python-c88981ad32e2">Tuples in python</a>, <a href="https://medium.com/@thanmai.chandaka/finding-handelling-missing-values-5f3eaf26c4c9">Finding &amp; Handlling Missing Values</a>, <a href="https://medium.com/@thanmai.chandaka/simple-linear-regression-c28d45527e40">Linear Regression</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d89c1a893e1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Linear Regression]]></title>
            <link>https://medium.com/@thanmai.chandaka/simple-linear-regression-c28d45527e40?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/c28d45527e40</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 14:23:05 GMT</pubDate>
            <atom:updated>2022-10-14T14:23:05.835Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog talks about the concept of simple linear regression. Simple linear regression is a statistical strategy that permits us to sum up and study connections between two continuous or quantitative variables: One variable, meant A, is viewed as the predictor, explanatory, or independent variable. The other variable, meant B, is viewed as the response, outcome, or dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n7J9N5m95GFoqdaV.jpg" /></figure><p>In statistics, a simple linear regression model uses a single variable to predict the result of the other variable.</p><p>In layman terms, we can define linear regression as <strong>it is used for learning the linear relationship between the target and one or more forecasters</strong>, and it is probably one of the most popular and well inferential algorithms in statistics. Linear regression endeavours to demonstrate the connection between two variables by fitting a linear equation to observed information. One variable is viewed as an explanatory variable, and the other is viewed as a dependent variable.</p><p>In simple linear regression, we aim to reveal the relationship between a single independent variable or you can say input, and a corresponding dependent variable or output.</p><p>We can discuss this in a simple line as <strong>y = mx+c</strong></p><p>Where, <strong>c</strong> is the intercept and <strong>m</strong> is the slope or coefficient of <strong>x.</strong></p><p>Here, <strong>c</strong> and <strong>m</strong> are the coefficients (or parameters) that need to be estimated from the data.</p><p><strong>Intercept:</strong> An intercept is a point on the y-axis, through which the slope of the line passes. It is the y-coordinate of a point where a straight line or a curve intersects the y-axis. This is represented when we write the equation for a line, y = mx+c, where m is slope and c is the y-intercept.</p><p><strong>Slope:</strong> The slope is a numerical value that describes the steepness of a line and is usually determined by calculating the ratio of the vertical distance to the horizontal distance (rise over run) between two points.</p><p>We can also discuss this in the form of a graph and here is a sample simple linear regression model graph. Thus, in this whole blog, you will get to learn so many new things about simple linear regression in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hCTxE8aJp09EP-Ak.png" /></figure><p><strong>Best Fit Line:</strong></p><p>We know that scatter plot is used to see how two numeric variables are related to each other and often if there is a linear relationship, we try to fit a line. But we cannot call any line as the Best Fit Line.</p><p>Our data contains a set of values for dependent variable (denoted by y) and independent variable/s (denoted by X) and a best fit line is the one for which the Residual Sum of Squares of error terms is minimum. What are error terms? Let’s find out.</p><p>So there will be a ‘y’ value given by our line (we call it y_pred) and a ‘y’ value which is already present in our data (we call it y_actual). The difference between actual value (y_actual) and predicted value (y_pred) gives us the error term (e). There will be an error term associated with each X and y value.</p><p>This error term may be positive or negative. So we take square or all the error terms and sum it. This is called Residual Sum of Squares of error terms.</p><p><strong>Cost function: </strong>The cost function can be defined as an algorithm that measures accuracy for our hypothesis. It is the Root Mean Squared Error between the predicted value and true value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Mk7nH2QHndKd0M8VdWTrGg.png" /><figcaption>Formula for Cost Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*OH9P7h2i0LqreBL0.PNG" /></figure><p>If we closely observe the cost function above, the term inside the summation is the square error term. So, what exactly is happening in the function is, it is finding the difference between the hypothesis and the output. The error gives us an idea of how accurate our hypothesis is. If the error is large, our hypothesis may not be accurate enough. If the error is low, our hypothesis may be accurate enough. So, if the error is as minimum as possible, that would derive our most accurate hypothesis for further predictions.</p><p>The (1/n) term before the summation denotes the mean.</p><p>So the aim of linear regression is to find the best fit line for given <strong><em>yi </em></strong>and <strong><em>y</em></strong> variables such that the Residual Sum of Squares of errors is minimum. In mathematical terms this RSS is our cost function which we need to minimize. There are several minimization techniques, but the most used is Gradient Descent method.</p><p><strong>Gradient Descent: </strong>Gradient descent is a first-order iterative optimization algorithm for finding the minimum of a function (commonly called loss/cost functions in machine learning and deep learning).</p><p>To find a local minimum of a function using gradient descent, one takes steps proportional to the negative of the gradient (or approximate gradient) of the function at the current point. If, instead, one takes steps proportional to the positive of the gradient, one approaches a local maximum of that function; the procedure is then known as gradient ascent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pInF6lj25Oz3X7m3.jpg" /></figure><p><strong>Loss Function: </strong>The Loss Function tells us how badly our machine performed and what’s the distance between the predictions and the actual values. There are many different Loss Functions for many different problems and I’m going to teach you the famous ones.</p><p><strong>Mean Squared Error:</strong> The Mean Squared Error or MSE calculates the squared error or in other words, the squared difference between the actual output and the predicted output for each sample. Sum them up and take their average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*343pcFES-5BC4uxG" /></figure><p><strong>Mean Absolute Error:</strong> Very similar to MSE but instead of squaring the distance, we take the absolute value of the error. We take the absolute value of the error rather than squaring it. Measures the average magnitude of the error across the predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*75Xa67cPOkTPhMa4.png" /></figure><p><strong>Root Mean Square Error:</strong> Root mean square error is the square root of the mean square, which is the arithmetic mean of the squares of a group of values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*gmYLiAgs1VNPXkCu" /></figure><p><strong>Closing Remarks: </strong>Please let me know if you have any questions in the comments section.</p><p>Please check my previous blogs on <a href="https://medium.com/@thanmai.chandaka/lists-in-python-a01879e7f237">Lists in Python</a>, <a href="https://medium.com/@thanmai.chandaka/tuples-in-python-c88981ad32e2">Tuples in python</a>, <a href="https://medium.com/@thanmai.chandaka/finding-handelling-missing-values-5f3eaf26c4c9">Finding &amp; Handlling Missing Values</a>.</p><p>So there will be a ‘y’ value given by our line (we call it y_pred) and a ‘y’ value which is already present in our data (we call it y_true). The difference between y_true and y_pred gives us the error term (e). There will be an error term associated with each X and y value.</p><p>This error term may be positive or negative. So we take square or all the error terms and sum it. This is called <strong>Residual Sum of Squares</strong> of error terms.</p><p><strong>So the aim of linear regression is to find the best fit line for given X and y variables such that the Residual Sum of Squares of errors is minimum</strong>. In mathematical terms this RSS is our cost function which we need to minimize. There are several minimization techniques, but the most used is Gradient Descent method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c28d45527e40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding & Handelling Missing Values]]></title>
            <link>https://medium.com/@thanmai.chandaka/finding-handelling-missing-values-5f3eaf26c4c9?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3eaf26c4c9</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Mon, 03 Oct 2022 10:20:13 GMT</pubDate>
            <atom:updated>2022-10-03T10:20:13.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Missing Data can occur when no information is provided for one or more items or for a whole unit. Missing Data is a very big problem in a real-life scenarios. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mR268UqDdknAjoDF.png" /></figure><p>Before I begin, I’d like to point out that the code &amp; dataset in this blog post is available on my <a href="https://github.com/Thanmai3249/Finding-Handelling-Missing-Values">github</a>. For this exercise I’m using “Travel.csv” dataset.</p><p>First step is to load the file and look at the structure of the file. When you have a big dateset with high number of columns it is hard to look at each columns and study the types of columns.</p><pre>#Install the below libaries before importing<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><pre>df = pd.read_csv(&#39;Travel.csv&#39;)<br>df.head(5)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPh5uR86JIT_dMKvdOix4g.png" /></figure><p><strong>info() Method:</strong> The info() method prints information about the DataFrame. The information contains the number of columns, column labels, column data types, memory usage, range index, and the number of cells in each column (non-null values). Note: the info() method actually prints the info.</p><pre>df.info()</pre><pre><strong>Output:</strong><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 4888 entries, 0 to 4887<br>Data columns (total 20 columns):<br> #   Column                    Non-Null Count  Dtype  <br>---  ------                    --------------  -----  <br> 0   CustomerID                4888 non-null   int64  <br> 1   ProdTaken                 4888 non-null   int64  <br> 2   Age                       4662 non-null   float64<br> 3   TypeofContact             4863 non-null   object <br> 4   CityTier                  4888 non-null   int64  <br> 5   DurationOfPitch           4637 non-null   float64<br> 6   Occupation                4888 non-null   object <br> 7   Gender                    4888 non-null   object <br> 8   NumberOfPersonVisiting    4888 non-null   int64  <br> 9   NumberOfFollowups         4843 non-null   float64<br> 10  ProductPitched            4888 non-null   object <br> 11  PreferredPropertyStar     4862 non-null   float64<br> 12  MaritalStatus             4888 non-null   object <br> 13  NumberOfTrips             4748 non-null   float64<br> 14  Passport                  4888 non-null   int64  <br> 15  PitchSatisfactionScore    4888 non-null   int64  <br> 16  OwnCar                    4888 non-null   int64  <br> 17  NumberOfChildrenVisiting  4822 non-null   float64<br> 18  Designation               4888 non-null   object <br> 19  MonthlyIncome             4655 non-null   float64<br>dtypes: float64(7), int64(7), object(6)<br>memory usage: 763.9+ KB</pre><p><strong>describe() method:</strong> The describe() method returns description of the data in the DataFrame. If the DataFrame contains numerical data, the description contains these information for each column: count — The number of not-empty values. mean — The average (mean) value.</p><pre>df.describe().T</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*gbfRCtXK_w10l9-gxf0stg.png" /></figure><p><strong>Separating categorical and numerical columns in the data frame: </strong>To get the column names of the columns which satisfy the above conditions we can use “df.columns”. The below code gives column names which are objects and column names which are not objects.</p><pre>df.columns</pre><pre><strong>Output:</strong><br>Index([&#39;CustomerID&#39;, &#39;ProdTaken&#39;, &#39;Age&#39;, &#39;TypeofContact&#39;, &#39;CityTier&#39;,<br>       &#39;DurationOfPitch&#39;, &#39;Occupation&#39;, &#39;Gender&#39;, &#39;NumberOfPersonVisiting&#39;,<br>       &#39;NumberOfFollowups&#39;, &#39;ProductPitched&#39;, &#39;PreferredPropertyStar&#39;,<br>       &#39;MaritalStatus&#39;, &#39;NumberOfTrips&#39;, &#39;Passport&#39;, &#39;PitchSatisfactionScore&#39;,<br>       &#39;OwnCar&#39;, &#39;NumberOfChildrenVisiting&#39;, &#39;Designation&#39;, &#39;MonthlyIncome&#39;],<br>      dtype=&#39;object&#39;)</pre><p>As you can see below we separated the original data frame into 2 and assigned them new variables. One for for categorical variables and one for non-categorical variables.</p><pre># Printing all the categorical columns<br>categorical_col = [fea for fea in df.columns if df[fea].dtype == &#39;O&#39;]<br>print(&#39;All Categorical columns&#39;,categorical_col)</pre><pre># Printing all the numerical columns<br>numerical_col = [fea for fea in df.columns if df[fea].dtype != &#39;O&#39;]<br>print(&#39;All Numerical columns&#39;,numerical_col)</pre><pre><strong>Output:<br></strong>All Categorical columns [&#39;TypeofContact&#39;, &#39;Occupation&#39;, &#39;Gender&#39;, &#39;ProductPitched&#39;, &#39;MaritalStatus&#39;, &#39;Designation&#39;]</pre><pre>All Numerical columns [&#39;CustomerID&#39;, &#39;ProdTaken&#39;, &#39;Age&#39;, &#39;CityTier&#39;, &#39;DurationOfPitch&#39;, &#39;NumberOfPersonVisiting&#39;, &#39;NumberOfFollowups&#39;, &#39;PreferredPropertyStar&#39;, &#39;NumberOfTrips&#39;, &#39;Passport&#39;, &#39;PitchSatisfactionScore&#39;, &#39;OwnCar&#39;, &#39;NumberOfChildrenVisiting&#39;, &#39;MonthlyIncome&#39;]</pre><p><strong>Finding Missing Values</strong></p><p>Ways to find missing values:</p><ol><li>Checking for missing values using isnull() and notnull()</li><li>Visualizing Missing Data using Seaborn heatmap()</li></ol><p><strong>Checking for missing values using isnull() and notnull():</strong> In order to check missing values in Pandas DataFrame, we use a function isnull() and notnull(). Both function help in checking whether a value is NaN or not. These function can also be used in Pandas Series in order to find null values in a series.</p><p><strong>Checking for missing values using isnull():</strong> In order to check null values in Pandas DataFrame, we use isnull() function this function return dataframe of Boolean values which are True for NaN values.</p><pre>df.isnull()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxPflf0jEhvmXDnnV_UwrQ.png" /></figure><p>To get how many missing values are in each column we use <strong>sum() </strong>along with <strong>isnull() </strong>which is shown below. This will sum up all the True’s in each column from the step above.</p><pre># if we use sum() we will get the count of null values in each column<br>df.isnull().sum()</pre><pre><strong>Output: </strong><br>CustomerID                    0<br>ProdTaken                     0<br>Age                         226<br>TypeofContact                25<br>CityTier                      0<br>DurationOfPitch             251<br>Occupation                    0<br>Gender                        0<br>NumberOfPersonVisiting        0<br>NumberOfFollowups            45<br>ProductPitched                0<br>PreferredPropertyStar        26<br>MaritalStatus                 0<br>NumberOfTrips               140<br>Passport                      0<br>PitchSatisfactionScore        0<br>OwnCar                        0<br>NumberOfChildrenVisiting     66<br>Designation                   0<br>MonthlyIncome               233<br>dtype: int64</pre><p><strong>Checking for missing values using notnull():</strong> In order to check null values in Pandas Dataframe, we use notnull() function this function return dataframe of Boolean values which are False for NaN values.</p><pre>df.notnull()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1q3jBaUkgNFXoTr5cHI4Q.png" /></figure><p><strong>Visualizing Missing Data using Seaborn heatmap(): </strong>First, we will use Seaborn’s heatmap() to make a heatmap of the data to visualize the missing data in each variable. Here we use the transposed boolean dataframe from isna() as input Seaborn’s heatmap() function.</p><pre>plt.figure(figsize=(10,6))<br>sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap=&#39;viridis&#39;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*kauByg7Y5jQ5YtFq3qpuEg.png" /></figure><p><strong>Handelling Missing Values</strong></p><p>Different ways to handle the missing values:</p><ol><li>Filling Nan values with 0</li><li>Filling Nan values with forward fill value</li><li>Filling Nan values with backward fill value</li><li>Interpolating missing values</li><li>Simple Imputation</li><li>Assigning an unique category (Only for categorical columns)</li><li>Imputation using Knn Imputer</li><li>Droping Nan values</li></ol><p><strong>Filling Nan values with 0: </strong>In this method we will fill the Nan values with zero(0).</p><pre>#filling nan values with 0.<br>new_df = df.fillna(0)<br>#checking for null values after filling nan values with 0.<br>new_df.isnull().sum()</pre><pre><strong>Output:<br></strong>CustomerID                  0<br>ProdTaken                   0<br>Age                         0<br>TypeofContact               0<br>CityTier                    0<br>DurationOfPitch             0<br>Occupation                  0<br>Gender                      0<br>NumberOfPersonVisiting      0<br>NumberOfFollowups           0<br>ProductPitched              0<br>PreferredPropertyStar       0<br>MaritalStatus               0<br>NumberOfTrips               0<br>Passport                    0<br>PitchSatisfactionScore      0<br>OwnCar                      0<br>NumberOfChildrenVisiting    0<br>Designation                 0<br>MonthlyIncome               0<br>dtype: int64</pre><p>After filling the nan values with zero we can see that there are no null values existing in our dataset.</p><p><strong>Filling Nan values with forward fill value: </strong>If we use forward fill that simply means we are forwarding the previous value where ever we have NaN values.</p><pre>#filling nan values with forward values<br>ffill_df = df.fillna(method=&quot;ffill&quot;)<br>#checking for null values after filling nan values with forawrd val.<br>ffill_df.isnull().sum()</pre><pre><strong>Output:<br></strong>CustomerID                  0<br>ProdTaken                   0<br>Age                         0<br>TypeofContact               0<br>CityTier                    0<br>DurationOfPitch             0<br>Occupation                  0<br>Gender                      0<br>NumberOfPersonVisiting      0<br>NumberOfFollowups           0<br>ProductPitched              0<br>PreferredPropertyStar       0<br>MaritalStatus               0<br>NumberOfTrips               0<br>Passport                    0<br>PitchSatisfactionScore      0<br>OwnCar                      0<br>NumberOfChildrenVisiting    0<br>Designation                 0<br>MonthlyIncome               0<br>dtype: int64</pre><p><strong>Filling NaN values with backward fill value:</strong> If we use backward fill that simply means we are filling the Nan values with the values after the NaN value where ever we have NaN values.</p><pre>#filling nan values with backward values<br>bfill_df = df.fillna(method=&quot;bfill&quot;)<br>#checking for null values after filling nan values with back val.<br>bfill_df.head(5)</pre><pre><strong>Output:<br></strong>CustomerID                  0<br>ProdTaken                   0<br>Age                         0<br>TypeofContact               0<br>CityTier                    0<br>DurationOfPitch             0<br>Occupation                  0<br>Gender                      0<br>NumberOfPersonVisiting      0<br>NumberOfFollowups           0<br>ProductPitched              0<br>PreferredPropertyStar       0<br>MaritalStatus               0<br>NumberOfTrips               0<br>Passport                    0<br>PitchSatisfactionScore      0<br>OwnCar                      0<br>NumberOfChildrenVisiting    0<br>Designation                 0<br>MonthlyIncome               0<br>dtype: int64</pre><p><strong>Interpolating Missing values: </strong>Interpolation is a statistical method by which related known values are used to estimate an unknown price or potential yield of a security. Interpolation is achieved by using other established values that are located in sequence with the unknown value.</p><p>Types is interpolation:</p><p>1)<strong>Linear Interpolation:</strong> Linear interpolation is basically the estimation of an unknown value that falls within two known values.</p><pre>new_df = df.interpolate(method = &#39;linear&#39;)</pre><p>2)<strong>Interpolation through padding: </strong>Interpolation with help of padding simply means filling missing values with the same value present above them in the dataset. If the missing value is in the first row then this method will not work. While using this technique you also need to specify the limit which means how many NaN values to fill.</p><pre>new_df = df.interpolate(method = &#39;pad&#39;, limit = 2)</pre><p>3)<strong>Polinomial Intepolation:</strong> In Polynomial Interpolation you need to specify an order. It means that polynomial interpolation is filling missing values with the lowest possible degree that passes through available data points. The polynomial Interpolation curve is like the trigonometric sin curve or assumes it like a parabola shape.</p><pre>new_df = df.interpolate(method = &#39;polynomial&#39;, order = 2)</pre><p><strong>Simple Imputation: </strong>This method involves utilizing a numerical summary of the variable where the missing value occurred (that is using the feature or variable’s central tendency summary, such as mean, median, and mode).</p><p>When you use this strategy to fill in the missing values, you need to evaluate the variable’s distribution to determine which central tendency summary to apply.</p><p>You use this method in the MCAR category. And you implement it in Python using the SimpleImputer transformer in the Scikit-learn library.</p><p>We can use Simple Imputation for all numerical and categorical values also.</p><pre># Replacing nan values with median in AGe column<br>from sklearn.impute import SimpleImputer<br>#Specify the strategy to be the median class<br>fea_transformer = SimpleImputer(strategy=&quot;median&quot;)<br>values = fea_transformer.fit_transform(df[[&#39;Age&#39;]])<br>#pd.DataFrame(values)</pre><pre># Replacing the column values with new values<br>df.Age= values<br>df.isnull().sum()</pre><pre><strong>Output: <br></strong>CustomerID                    0<br>ProdTaken                     0<br>Age                           0<br>TypeofContact                25<br>CityTier                      0<br>DurationOfPitch               0<br>Occupation                    0<br>Gender                        0<br>NumberOfPersonVisiting        0<br>NumberOfFollowups            45<br>ProductPitched                0<br>PreferredPropertyStar        26<br>MaritalStatus                 0<br>NumberOfTrips               140<br>Passport                      0<br>PitchSatisfactionScore        0<br>OwnCar                        0<br>NumberOfChildrenVisiting     66<br>Designation                   0<br>MonthlyIncome               233<br>dtype: int64</pre><p>We can see that, in the output there are no Nan values in the in the column after applying simple imputer on the particular column. We can repeate the process for all the columns with nan values including categorical columns by changing the strategy to most_frequent.</p><p><strong>Assigning An Unique Category (For categorical columns only): </strong>A categorical feature will have a definite number of possibilities, such as gender, for example. Since they have a definite number of classes, we can assign another class for the missing values.</p><pre>df = pd.read_csv(&#39;Travel.csv&#39;)<br>print(&#39;count of Nan values in TypeofContact column is&#39;,df[&#39;TypeofContact&#39;].isnull().sum())</pre><pre><strong>Output:<br></strong>count of Nan values in TypeofContact column is 25</pre><pre># Now let us see how many categories of values we have in TypeofContact column <br>print(df[&#39;TypeofContact&#39;].value_counts())</pre><pre><strong>Output:<br></strong>Self Enquiry       3444<br>Company Invited    1419<br>Name: TypeofContact, dtype: int64</pre><pre># let&#39;s add another unique categoty<br>df[&#39;TypeofContact&#39;] = df[&#39;TypeofContact&#39;].fillna(&#39;Other&#39;)<br># Now let&#39;s check the unique value count of TypeofContact column again<br>print(&#39;count of Nan values in TypeofContact column is&#39;,df[&#39;TypeofContact&#39;].isnull().sum())</pre><pre><strong>Output:<br></strong>count of Nan values in TypeofContact column is 0</pre><p><strong>Imputation using the KNNimputer(): </strong>KNNimputer is a scikit-learn class used to fill out or predict the missing values in a dataset. It is a more useful method which works on the basic approach of the KNN algorithm rather than the naive approach of filling all the values with mean or the median. In this approach, we specify a distance from the missing values which is also known as the K parameter. The missing value will be predicted in reference to the mean of the neighbours.</p><pre>from sklearn.impute import KNNImputer</pre><pre>df = pd.read_csv(&quot;Products_Data.csv&quot;)<br>del df[&#39;Date&#39;]<br>imputer = KNNImputer(n_neighbors=2)<br>df_filled = imputer.fit_transform(df)<br>df_filled</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*0xrbHMr6Ck2q9CsaWcULxw.png" /></figure><p><strong>Droping Nan Values:</strong> Pandas DataFrame dropna() function is used to remove rows and columns with Null/NaN values. By default, this function returns a new DataFrame and the source DataFrame remains unchanged. We can create null values using None, pandas.NaT, and numpy.nan variables.</p><pre>#Droping null values<br>df = df.dropna()<br>df</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-EkW7rjpAjyh_SPgncwDQ.png" /></figure><p><strong>Closing Remarks: </strong>Please let me know if you have any questions in the comments section.</p><p>Please check my previous blogs on <a href="https://medium.com/@thanmai.chandaka/lists-in-python-a01879e7f237">Lists in Python</a>, <a href="https://medium.com/@thanmai.chandaka/tuples-in-python-c88981ad32e2">Tuples in python</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3eaf26c4c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuples in Python]]></title>
            <link>https://medium.com/@thanmai.chandaka/tuples-in-python-c88981ad32e2?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/c88981ad32e2</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 10:01:39 GMT</pubDate>
            <atom:updated>2022-09-28T10:01:39.261Z</atom:updated>
            <content:encoded><![CDATA[<p>You will discover all there is to know about Python tuples in this post. More precisely, you should understand what tuples are, how to make them, when to utilise them, and the several approaches you can employ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4NuKKjfoZiMNJ93i.png" /></figure><p>Before I begin, I’d like to point out that the code in this blog post is available on my <a href="https://github.com/Thanmai3249/Python-Tuples">github</a>.</p><p><strong>Definition:</strong> A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.</p><p>A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them.</p><pre># Defining a tuple<br>my_tuple = (1,2,3,4,5)<br>print(my_tuple)</pre><pre># # Creating tuple without using parentheses: Tuple packing<br>my_tuple = 1, 2, 3, 4, 5<br>print(my_tuple)</pre><pre># Tuple unpacking<br>a, b, c, d, e = my_tuple<br>print(a)<br>print(b)<br>print(c)</pre><pre><strong>Output:<br></strong>(1, 2, 3, 4, 5)<br>(1, 2, 3, 4, 5)<br>1<br>2<br>3</pre><p>A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).</p><pre># Creating empty tuple<br>t = ()<br>print(t)</pre><pre># Tuple with mixed datatypes<br>my_tuple = (1, 2, 3, 4, 5, 28.3, &#39;abc&#39;)<br>print(my_tuple)</pre><pre># Nested tuple<br>nested_tuple = (1, 2, 3, 4, 5, [&#39;abc&#39;, &#39;def&#39;, 24.55, 7], (9, 10,11))<br>print(nested_tuple)</pre><pre><strong>Output:<br></strong>()<br>(1, 2, 3, 4, 5, 28.3, &#39;abc&#39;)<br>(1, 2, 3, 4, 5, [&#39;abc&#39;, &#39;def&#39;, 24.55, 7], (9, 10, 11))</pre><p>To write a tuple containing a single value you have to include a comma, even though there is only one value −</p><pre>t = &quot;hello&quot;,<br>print(t)<br>print(type(t))</pre><pre>t = (&quot;hello&quot;,)<br>print(t)<br>print(type(t))</pre><pre>t = &quot;hello&quot;<br>print(t)<br>print(type(t))</pre><pre>t = (&quot;hello&quot;)<br>print(t)<br>print(type(t))</pre><pre><strong>Output:<br></strong>(&#39;hello&#39;,)<br>&lt;class &#39;tuple&#39;&gt;<br>(&#39;hello&#39;,)<br>&lt;class &#39;tuple&#39;&gt;<br>hello<br>&lt;class &#39;str&#39;&gt;<br>hello<br>&lt;class &#39;str&#39;&gt;</pre><p>There are various ways in which we can access the elements of a tuple.</p><p><strong>Indexing: </strong>We can use the index operator [] to access an item in a tuple, where the index starts from 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*9a2pq_uKCB2ZRV5b.jpg" /><figcaption>Tuple Indexing</figcaption></figure><p>Nested tuples are accessed using nested indexing, as shown in the example below.</p><pre>my_tuple = (1, 2, 3, 4, 5,28.3,&#39;abc&#39;, [&#39;math&#39;,&#39;physics&#39;,90.5,100], (&#39;chemistry&#39;,&#39;computers&#39;,70.9,80))<br>print(my_tuple)</pre><pre># first entry<br>print(my_tuple[0])</pre><pre>#fourth entry<br>print(my_tuple[3])</pre><pre>#sixth entry<br>print(my_tuple[5])</pre><pre>#eighth entry<br>print(my_tuple[7])</pre><pre>#first item in eighth entry --&gt; Nested indexing<br>print(my_tuple[7][0])</pre><pre>#last entry<br>print(my_tuple[8])</pre><pre>#last item in last entry --&gt; Nested indexing<br>print(my_tuple[8][3])</pre><pre><strong>Output:<br></strong>(1, 2, 3, 4, 5, 28.3, &#39;abc&#39;, [&#39;math&#39;, &#39;physics&#39;, 90.5, 100], (&#39;chemistry&#39;, &#39;computers&#39;, 70.9, 80))<br>1<br>4<br>28.3<br>[&#39;math&#39;, &#39;physics&#39;, 90.5, 100]<br>math<br>(&#39;chemistry&#39;, &#39;computers&#39;, 70.9, 80)<br>80</pre><p><strong>Negative Indexing:</strong> Python allows negative indexing for its sequences. In negative indexing, the indexing of elements starts from the end of the tuple. That is the last element of the tuple is said to be at a position at -1 and the previous element at -2 and goes on till the first element.</p><pre># last entry<br>print(my_tuple[-1])</pre><pre>#last item in last entry--&gt; Nested indexing<br>print(my_tuple[-1][-1])</pre><pre>#fourth entry<br>print(my_tuple[-2])</pre><pre>#last item in eighth entry--&gt; Nested indexing<br>print(my_tuple[-2][-1])</pre><pre>#fifth entry<br>print(my_tuple[-4])</pre><pre>#fourth entry<br>print(my_tuple[-5])</pre><pre>#fourth entry<br>print(my_tuple[-6])</pre><pre><strong>Output:<br></strong>(&#39;chemistry&#39;, &#39;computers&#39;, 70.9, 80)<br>80<br>[&#39;math&#39;, &#39;physics&#39;, 90.5, 100]<br>100<br>28.3<br>5<br>4</pre><p><strong>Tuple Slicing:</strong> Tuple slicing is a frequent practice in Python, and it is the most prevalent technique used by programmers to solve efficient problems. Consider a Python tuple. You must slice a tuple in order to access a range of elements in it. One method is to utilize the colon as a simple slicing operator (:).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/0*8lL0QDVEBoBLDaLa.png" /><figcaption>Tuple Slicing in Python</figcaption></figure><pre><strong>Syntax:</strong> tuple[Start : Stop : Stride]</pre><p>The slice operator allows you to specify where to begin slicing, where to stop slicing, and what step to take. Tuple slicing creates a new tuple from an old one.</p><pre>my_tuple = (&#39;p&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;,&#39;e&#39;)</pre><pre># elements from index 2 to index 4<br>print(my_tuple[2:5])</pre><pre># elements from index 5 to end<br>print(my_tuple[5:])</pre><pre># elements from index 0 to 10 by taking 2 jumps<br>print(my_tuple[0:10:2])</pre><pre># elements beginning to end<br>print(my_tuple[:])</pre><pre><strong>Output:<br></strong>(&#39;t&#39;, &#39;h&#39;, &#39;o&#39;)<br>(&#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;, &#39;e&#39;)<br>(&#39;p&#39;, &#39;t&#39;, &#39;o&#39;, &#39;t&#39;, &#39;p&#39;)<br>(&#39;p&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;, &#39;e&#39;)</pre><p><strong>Slice with Negative Indices: </strong>You can also specify negative indices while slicing a list.</p><pre># elements from index 0 to 6<br>print(my_tuple[-7:-1])</pre><pre># elements from index 0 to 6 by taking 2 jumps<br>print(my_tuple[-7:-1:2])</pre><pre># reversing the list<br>print(my_tuple[::-1])</pre><pre>#printing empty list<br>print(my_tuple[0:7:-1])</pre><pre><strong>Output:</strong><br>(&#39;o&#39;, &#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;)<br>(&#39;o&#39;, &#39;t&#39;, &#39;p&#39;)<br>(&#39;e&#39;, &#39;l&#39;, &#39;p&#39;, &#39;u&#39;, &#39;t&#39;, &#39;n&#39;, &#39;o&#39;, &#39;h&#39;, &#39;t&#39;, &#39;y&#39;, &#39;p&#39;)<br>()</pre><p><strong>Updating Tuples: </strong>Tuples are immutable which means you cannot update or change the values of tuple elements.</p><pre># values in tuple can&#39;t be changes<br>my_tuple = (&#39;p&#39;,&#39;y&#39;,&#39;t&#39;,&#39;h&#39;,&#39;o&#39;,&#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;,&#39;e&#39;,[1,2,3])<br>my_tuple[0] = &#39;xyz&#39;<br>print(my_tuple)</pre><pre><strong>&gt;&gt;TypeError</strong>: &#39;tuple&#39; object does not support item assignment</pre><pre>my_tuple = (&#39;p&#39;, &#39;y&#39;, &#39;t&#39;,&#39;h&#39;,&#39;o&#39;,&#39;n&#39;,&#39;t&#39;,&#39;u&#39;,&#39;p&#39;,&#39;l&#39;,&#39;e&#39;,(1,2,3))<br>my_tuple[11][0]= 100<br>print(my_tuple)</pre><pre><strong>&gt;&gt;TypeError</strong>: &#39;tuple&#39; object does not support item assignment</pre><pre># item of list element in a tuple can be changed<br>my_tuple = (&#39;p&#39;,&#39;y&#39;,&#39;t&#39;,&#39;h&#39;,&#39;o&#39;,&#39;n&#39;,&#39;t&#39;,&#39;u&#39;,&#39;p&#39;, &#39;l&#39;,&#39;e&#39;,[1,2,3])<br>my_tuple[11][0]= 100<br>print(my_tuple)</pre><pre><strong>Output:<br></strong>(&#39;p&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;, &#39;e&#39;, [100, 2, 3])</pre><p>We can use + operator to combine two tuples. This is called <strong>concatenation</strong>. We can also <strong>repeat</strong> the elements in a tuple for a given number of times using the * operator. Both + and * operations result in a new tuple.</p><pre># Concatenation<br>print((1, 2, 3) + (4, 5, 6) + (8, 9, 10))</pre><pre># Repeat<br>print((&quot;python&quot;,) * 5)</pre><pre><strong>Output:<br></strong>(1, 2, 3, 4, 5, 6, 8, 9, 10)<br>(&#39;python&#39;, &#39;python&#39;, &#39;python&#39;, &#39;python&#39;, &#39;python&#39;)</pre><p><strong>Tuple Methods:</strong> Methods that add items or remove items are not available with tuple. Only the following two methods are available.</p><ol><li><strong>count():</strong> Returns the number of times a specified value occurs in a tuple. <strong>tuple.count(elem)</strong></li><li><strong>index():</strong> Searches the tuple for a specified value and returns the position of where it was found. <strong>tuple.index(elem)</strong></li></ol><pre>my_tuple = (&#39;p&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;,&#39;e&#39;)<br>print(my_tuple.count(&#39;t&#39;))<br>print(my_tuple.index(&#39;o&#39;))</pre><pre><strong>Output:<br></strong>2<br>4</pre><p><strong>Tuple Functions: </strong>Python includes the following tuple functions −</p><ol><li>len(): Gives the total length of the tuple.<strong> len(tuple)</strong></li><li>max(): Returns item from the tuple with max value. <strong>max(tuple)</strong></li><li>min(): Returns item from the tuple with min value. <strong>min(tuple)</strong></li><li>tuple(): Converts a list into tuple. <strong>tuple(seq)</strong></li></ol><pre>my_tuple = (&#39;p&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;, &#39;t&#39;, &#39;u&#39;, &#39;p&#39;, &#39;l&#39;,&#39;e&#39;)</pre><pre>print(len(my_tuple))<br>print(max(my_tuple))<br>print(min(my_tuple))<br>print(tuple([1,2,3,4,5]))</pre><pre><strong>Output:<br></strong>11<br>y<br>e<br>(1, 2, 3, 4, 5)</pre><p><strong>Closing Remarks: </strong>Please let me know if you have any questions in the comments section.</p><p>Please check my previous blog on <a href="https://medium.com/@thanmai.chandaka/lists-in-python-a01879e7f237">Lists in Python</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c88981ad32e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lists in Python]]></title>
            <link>https://medium.com/@thanmai.chandaka/lists-in-python-a01879e7f237?source=rss-297e54599a81------2</link>
            <guid isPermaLink="false">https://medium.com/p/a01879e7f237</guid>
            <dc:creator><![CDATA[Thanmai Chandaka]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 13:53:01 GMT</pubDate>
            <atom:updated>2022-09-27T14:12:57.458Z</atom:updated>
            <content:encoded><![CDATA[<p>With the aid of examples, we will learn how to create lists, change list elements, remove list elements, and perform other list operations in this course.</p><p>Before I begin, I’d like to point out that the code in this blog post is available on my <a href="https://github.com/Thanmai3249/Python-Lists">github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3OCQ7w8LSbgByLlJ.png" /></figure><p>Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.</p><p><strong>Definition: </strong>A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].</p><pre>#Defining a list<br>List = [1,2,3,4,5]</pre><p>A list can have any number of items and they may be of different types (integer, float, string, etc.).</p><pre># list with mixed data types<br>l = [1,2,3,4,5 ,&#39;tan&#39;, 64.5 ]<br>l</pre><p>A list can also have another list as an item. This is called a nested list.</p><pre># nested list<br>nested_l = [&quot;tan&quot;, [8, 4, 6], [2.3, 5]]</pre><p><strong>List Indexing: </strong>List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zhmhj_IiZEQ_aZey.png" /><figcaption>List Indexing in Python</figcaption></figure><p>When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.</p><pre># List Indexing<br>my_list = [1, 2, 3, 4, 5,&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 45.5]</pre><pre># first item<br>print(my_list[0])</pre><pre># second item<br>print(my_list[1])</pre><pre># third item<br>print(my_list[2])</pre><pre># last item<br>print(my_list[8])</pre><pre><strong>Output:<br></strong>1<br>2<br>3<br>45.5</pre><p>We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.</p><pre>my_list[0:5] # Printing 0 to 5 indexes data from a list</pre><pre><strong>Output:<br></strong>[1, 2, 3, 4, 5]</pre><p>Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on</p><pre>my_list = [1, 2, 3, 4, 5,&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 45.5]</pre><pre># last item<br>print(my_list[-1])</pre><pre># eighth item<br>print(my_list[-2])</pre><pre># seventh item<br>print(my_list[-3])</pre><pre># sixth item<br>print(my_list[-4])</pre><pre># fifth last item<br>print(my_list[-5])</pre><pre><br><strong>Output:<br></strong>45.5<br>c<br>b<br>a<br>5</pre><p><strong>List Slicing in Python:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZyLXjcYZo51hkcAx.png" /><figcaption>List Slicing Operations in Python</figcaption></figure><p>List slicing is a common practise in Python, and it is the most commonly used technique for programmers to solve efficient problems. Consider a Python list. To access a range of elements in a list, you must slice it. One method is to use the simple slicing operator, i.e. colon (:)</p><p>With this operator, one can specify where to begin slicing, where to end slicing, and the step. List slicing creates a new list from an existing one.</p><pre><strong>Syntax:</strong> Lst<strong>[</strong> Initial <strong>:</strong> End <strong>:</strong> IndexJump <strong>]</strong></pre><p>Below is a simple program, to display a whole list using slicing.</p><pre># List slicing in Python</pre><pre>my_list = [&#39;t&#39;, &#39;h&#39;, &#39;a&#39;, &#39;n&#39;, &#39;m&#39;, &#39;a&#39;, &#39;i&#39;]</pre><pre># elements from index 2 to index 4<br>print(my_list[2:5])</pre><pre># elements from index 5 to end<br>print(my_list[5:])</pre><pre># elements from index 0 to 6 by taking 2 jumps<br>print(my_list[0:6:2])</pre><pre># elements beginning to end<br>print(my_list[:])</pre><pre><strong>Output:<br></strong>[&#39;a&#39;, &#39;n&#39;, &#39;m&#39;]<br>[&#39;a&#39;, &#39;i&#39;]<br>[&#39;t&#39;, &#39;a&#39;, &#39;m&#39;]<br>[&#39;t&#39;, &#39;h&#39;, &#39;a&#39;, &#39;n&#39;, &#39;m&#39;, &#39;a&#39;, &#39;i&#39;]</pre><p><strong>Slice with Negative Indices: </strong>You can also specify negative indices while slicing a list.</p><pre># elements from index 0 to 6<br>print(my_list[-7:-1])</pre><pre># elements from index 0 to 6 by taking 2 jumps<br>print(my_list[-7:-1:2])</pre><pre># reversing the list<br>print(my_list[::-1])</pre><pre>#printing empty list<br>print(my_list[0:7:-1])</pre><pre><strong>Output:<br></strong>[&#39;t&#39;, &#39;h&#39;, &#39;a&#39;, &#39;n&#39;, &#39;m&#39;, &#39;a&#39;]<br>[&#39;t&#39;, &#39;a&#39;, &#39;m&#39;]<br>[&#39;i&#39;, &#39;a&#39;, &#39;m&#39;, &#39;n&#39;, &#39;a&#39;, &#39;h&#39;, &#39;t&#39;]<br>[]</pre><p>The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. Since lists are indexed, lists can have items with the same value.</p><pre>List = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Cherry&#39;, &#39;Apple&#39;]<br>List</pre><pre><strong>Output:<br></strong>[&#39;Apple&#39;, &#39;Banana&#39;, &#39;Cherry&#39;, &#39;Apple&#39;]</pre><p><strong>List Functions: </strong>Some significant Python list built-in functions are listed below.</p><p><strong>len():</strong> To determine how many items a list has, use the len() function:</p><pre>l = [1,2,3,4,5 ,&#39;tan&#39;, 64.5 ]<br>len(l)</pre><pre><strong>Output: <br></strong>7</pre><p><strong>type()</strong>: From Python’s perspective, lists are defined as objects with the data type ‘list’:</p><pre>l = [1,2,3,4,5 ,&#39;tan&#39;, 64.5 ]<br>print(type(l))</pre><pre><strong>Output:<br></strong>&lt;class &#39;list&#39;&gt;</pre><p><strong>min() &amp; max(): </strong>Gets the smallest &amp; largest item in a sequence.</p><pre>#integers<br>l1 = [-1, 3, 5.5, 6, -7, 0]<br>print(min(l1))<br>print(max(l1))</pre><pre><strong>Output:<br></strong>-7<br>6</pre><pre>#strings<br>l2 = [&#39;tan&#39;, &#39;cos&#39;,&#39;cosec&#39;, &#39;sec&#39;]<br>print(min(l2))<br>print(max(l2))</pre><pre><strong>Output:<br></strong>cos<br>tan</pre><p><strong>Delete List Elements: </strong>Using the Python del statement, we can remove one or more items from a list. It has the ability to completely delete the list.</p><pre># Deleting list items<br>my_list = [&#39;t&#39;, &#39;h&#39;, &#39;a&#39;, &#39;n&#39;, &#39;m&#39;, &#39;a&#39;, &#39;i&#39;]</pre><pre>&gt;&gt;&gt;&gt;del list[index]</pre><pre># delete one item<br>del my_list[2]</pre><pre>print(my_list)</pre><pre># delete multiple items<br>del my_list[1:5]</pre><pre>print(my_list)</pre><pre># delete the entire list<br>del my_list</pre><pre><strong>Output:<br></strong>[&#39;t&#39;, &#39;h&#39;, &#39;n&#39;, &#39;m&#39;, &#39;a&#39;, &#39;i&#39;]<br>[&#39;t&#39;, &#39;i&#39;]</pre><p><strong>List Methods: </strong>Working with lists is incredibly simple in Python thanks to its wealth of handy list functions. Here are some of the list approaches that are frequently used.</p><p>append()<br>extend()<br>insert()<br>remove()<br>pop()<br>index()<br>count()<br>sort()<br>reverse()<br>copy()<br>clear()</p><ol><li><strong>append(): </strong>Append function<strong> </strong>adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. <strong>list.append(elem)</strong></li><li><strong>extend(): </strong>Extend function<strong> </strong>adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). <strong>list.extend(list2)</strong></li><li><strong>insert(): </strong>Insert function<strong> </strong>inserts the element at the given index, shifting elements to the right. <strong>list.insert(index, elem)</strong></li><li><strong>remove():</strong> Remove function searches for the first instance of the given element and removes it. <strong>list.remove(elem)</strong></li><li><strong>pop():</strong> Pop function removes and returns the element at the given index. Returns the rightmost element if index is omitted. <strong>list.pop(index)</strong></li><li><strong>index():</strong> Index function searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear. <strong>list.index(elem)</strong></li><li><strong>count():</strong> Count function returns the count of the number of items passed as an argument. <strong>list.count(elem)</strong></li><li><strong>sort():</strong> Sort function sorts the list in place. <strong>list.sort()</strong></li><li><strong>reverse():</strong> Reverse function reverses the list in place. <strong>list.reverse()</strong></li><li><strong>copy():</strong> Copy function returns a shallow copy of the list. <strong>list.copy()</strong></li><li><strong>clear():</strong> Clear function removes all items from the list. <strong>list.clear()</strong></li></ol><pre>list_methods = [&#39;sine&#39;, &#39;cos&#39;, &#39;tan&#39;, &#39;cosec&#39;, &#39;sec&#39;, &#39;cot&#39;]<br>list_methods.append(&#39;case&#39;)<br>print(list_methods)</pre><pre>list_methods.extend([1,2,3,4,5,6,7,7,7,7])<br>print(list_methods)</pre><pre>list_methods.insert(0, &#39;xyz&#39;)<br>print(list_methods)</pre><pre>list_methods.remove(&#39;xyz&#39;)<br>print(list_methods)</pre><pre>list_methods.pop(1) <br>print(list_methods)</pre><pre>print(list_methods.index(&#39;case&#39;))</pre><pre>print(list_methods.count(7))</pre><pre>lst = [1,5,3,4,6,7,3,2,9,4,0,10,22,-11]<br>lst.sort() <br>print(lst)</pre><pre>list_methods.reverse() <br>print(list_methods)</pre><pre>list_methods.copy() <br>print(list_methods)</pre><pre>list_methods.clear() <br>print(list_methods)</pre><pre><strong>Output:<br></strong>[&#39;sine&#39;, &#39;cos&#39;, &#39;tan&#39;, &#39;cosec&#39;, &#39;sec&#39;, &#39;cot&#39;, &#39;case&#39;]<br>[&#39;sine&#39;, &#39;cos&#39;, &#39;tan&#39;, &#39;cosec&#39;, &#39;sec&#39;, &#39;cot&#39;, &#39;case&#39;, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7]<br>[&#39;xyz&#39;, &#39;sine&#39;, &#39;cos&#39;, &#39;tan&#39;, &#39;cosec&#39;, &#39;sec&#39;, &#39;cot&#39;, &#39;case&#39;, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7]<br>[&#39;sine&#39;, &#39;cos&#39;, &#39;tan&#39;, &#39;cosec&#39;, &#39;sec&#39;, &#39;cot&#39;, &#39;case&#39;, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7]<br>[&#39;sine&#39;, &#39;tan&#39;, &#39;cosec&#39;, &#39;sec&#39;, &#39;cot&#39;, &#39;case&#39;, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7]<br>5<br>4<br>[-11, 0, 1, 2, 3, 3, 4, 4, 5, 6, 7, 9, 10, 22]<br>[7, 7, 7, 7, 6, 5, 4, 3, 2, 1, &#39;case&#39;, &#39;cot&#39;, &#39;sec&#39;, &#39;cosec&#39;, &#39;tan&#39;, &#39;sine&#39;]<br>[7, 7, 7, 7, 6, 5, 4, 3, 2, 1, &#39;case&#39;, &#39;cot&#39;, &#39;sec&#39;, &#39;cosec&#39;, &#39;tan&#39;, &#39;sine&#39;]<br>[]</pre><p><strong>Closing Remarks: </strong>Please let me know if you have any questions in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a01879e7f237" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>