<?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 Mahadev Easwar on Medium]]></title>
        <description><![CDATA[Stories by Mahadev Easwar on Medium]]></description>
        <link>https://medium.com/@mahadeveaswar?source=rss-354de2ec0117------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oFcreWBi8C2mfRcBTpP_aw.jpeg</url>
            <title>Stories by Mahadev Easwar on Medium</title>
            <link>https://medium.com/@mahadeveaswar?source=rss-354de2ec0117------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:09:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahadeveaswar/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[The AI Imposter Syndrome: The Quiet Anxiety of Building With AI]]></title>
            <link>https://pub.towardsai.net/the-ai-imposter-syndrome-the-quiet-anxiety-of-building-with-ai-f5dbb2d0016a?source=rss-354de2ec0117------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5dbb2d0016a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mahadev Easwar]]></dc:creator>
            <pubDate>Thu, 07 May 2026 20:01:01 GMT</pubDate>
            <atom:updated>2026-05-07T20:01:01.409Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Did I actually build this, or did AI?</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWpINgN0ClyrY00N1YU3Rw.png" /><figcaption>The new default: ask first, build faster, question what it means later.</figcaption></figure><p>There’s often a question that comes up after you’ve shipped something:</p><p><em>How much of this was actually my work?</em></p><p>Claude, GPT, Cursor, whatever the tool, AI has become a default first move for many developers, myself included. Before we write, before we search, sometimes before we’ve fully formed the thought, we ask.</p><p>It’s fast. It works.</p><p>But somewhere in that speed, a quieter doubt creeps in:</p><p><em>If the tool helped me build this quickly, how much of it was really mine?</em></p><p>I used to spend more time getting to the first version. There was always some friction between the idea and the thing I could actually test: scaffolding, syntax, setup, documentation, the small mechanical steps that come with starting anything new.</p><p>Now there’s less of that friction.</p><p>And that’s when I realized something important:</p><p><strong>The time I saved was not where my value came from.</strong></p><h3>The Trap: Mistaking Friction for Value</h3><p>When AI writes code in 30 seconds, the struggle disappears. And with it, the validation that used to come from struggling.</p><p>For a long time, effort was the receipt. If you spent two hours writing a function, you felt like you had earned it. You had wrestled with the syntax, worked through the edge cases, searched the docs, made the mistakes, and finally arrived at something that worked.</p><p>That process made the result feel legitimate.</p><p>AI changes that flow.</p><p>Now the first version can appear almost immediately. The blank page is gone. The boilerplate is gone. The slow crawl from idea to prototype is compressed into a prompt and a response.</p><p>And that compression can feel suspicious.</p><p>If I did not struggle with the blank page, was I really thinking?</p><p>If I did not remember every method name, am I still a skilled engineer?</p><p>If AI suggested three approaches and I chose one, did I make the decision, or did I just approve it?</p><blockquote><strong><em>That is the trap: mistaking friction for value.</em></strong></blockquote><p>Because for years, friction was easy to measure. Time spent. Lines written. Errors fixed. Documentation searched. The visible signs of effort made the work feel earned.</p><p>But AI removes many of those signs.</p><p>It gives you the output without the familiar proof that you earned your way there. And when that proof disappears, it becomes harder to tell the difference between using a tool well and letting the tool do the work for you.</p><p>That is where the anxiety comes from. Not because AI helped.</p><p>But because the old signals of competence are starting to break.</p><p>That is where the real risk begins.</p><h3>The Dangerous Shortcut</h3><p>The obvious response is to say: fine, if AI can move this fast, let it make more of the decisions too.</p><p>And this is where things get dangerous.</p><p>Speed creates confidence. Confidence can start to feel like wisdom.</p><p>You ask AI for options. It gives you a recommendation with certainty. It sounds smart. It’s fast.</p><p>You implement it, it works, and for a moment you feel like you solved something.</p><p>But speed is not the same as thought. And convenience is not the same as correctness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zdk0xbp8v43sCB8a0XNmQA.png" /><figcaption>The shortcut looks efficient until the hidden debt shows up.</figcaption></figure><p>You ask AI how to handle data coming from three upstream sources with different schemas. It gives you a clean ETL pattern that looks good. You implement it because it’s fast and well-written.</p><p>Six weeks later, one upstream source changes its format slightly. Your pipeline silently starts dropping data. Nobody notices until the reporting team flags inconsistencies in the monthly numbers.</p><p>Nothing about the recommendation looked obviously wrong. That was the problem.</p><p>It fit the prompt. It followed a familiar pattern. It sounded like the kind of solution I might have arrived at myself.</p><p>And that is what makes the shortcut so easy to miss.</p><p>When the answer looks reasonable, it becomes easier to stop asking the second and third questions.</p><ul><li>What changes upstream?</li><li>What breaks downstream?</li><li>What happens when the data is late, incomplete, duplicated, or just slightly different than expected?</li><li>What downstream reports or dashboards depend on this data arriving correctly?</li></ul><blockquote>The obviously bad answer is easy to reject.</blockquote><blockquote>The reasonable one is what gets through.</blockquote><p>Speed without thinking creates debt, not progress.</p><p>And some of that debt shows up in you.</p><h4>The Skill You Stop Practicing</h4><p>If you let AI make enough decisions for you, something quieter starts to happen. You stop exercising one of the most important skills you have: the ability to decide.</p><p>Decision-making is a muscle. You build it by making choices, being wrong, learning the consequences, and understanding tradeoffs. You build it by sitting with ambiguity and choosing a direction anyway.</p><p>But when AI becomes the decision-maker, you become the approver.</p><p>You ask for options and pick the one that sounds smartest.</p><p><strong><em>You outsource the hard part, the thinking, and keep the easy part, the approval.</em></strong></p><p>That can still feel productive.</p><p>The ticket moves. The code ships. The dashboards look good.</p><p>But over time, the gap compounds silently. After enough moments of asking instead of deciding, you lose something real: the instinct to think through tradeoffs before reaching for the answer.</p><h3>The Context AI Does Not Have</h3><p>Here is where the gap between <em>working code</em> and <em>code that actually works in production</em> becomes clear.</p><p>AI does not know things like:</p><ul><li>you have API rate limits</li><li>you are sharing a database with twelve other services</li><li>a query scanning 50 million rows at 2 AM might affect a reporting pipeline</li><li>you are close to your monthly quota on a third-party service</li></ul><p>You know those things because you have lived with the system.</p><p>You remember the API that timed out instead of returning a clean error, the database lock that broke reporting, and the third-party bill that spiked because one loop made more calls than expected.</p><p>AI does not carry that history.</p><p>And that matters because the hard part is not always writing the code. A lot of the time, the hard part is knowing what the code is allowed to assume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqyA7ISoA-dmc3fPDaDDaw.png" /><figcaption>AI works with what it can see. You carry the rest.</figcaption></figure><h4>When the Code Was the Easy Part</h4><p>I worked recently on something that looked simple on paper: support a new request in a legacy system without breaking the existing flows the business still depended on.</p><p>On the surface, it looked like the kind of work AI should be good at.</p><p>Read the pattern. Generate the code. Clean up the flow. Move on.</p><p>And AI did help. It explained the existing structure, drafted pieces of code, and suggested cleaner ways to organize the logic.</p><p>But the important part was not writing the code.</p><p><strong>The code was visible. The risk was not.</strong></p><p>A cleaner redesign might have looked better in isolation. It might have separated the new behavior from the old behavior and made the system easier to reason about.</p><p>But this was not an isolated system.</p><p>Some of the awkward legacy configuration was load-bearing. Some dependencies would not show up in tests. Some breakage would only surface later in a reporting pipeline someone else owned.</p><p>So the right answer was not the cleanest design. It was the design that fit the system.</p><p>It preserved the existing flows, supported the new request, and avoided turning a small change into a larger rewrite.</p><p>That was the real work: understanding the system well enough to know when the clean answer was not the correct one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dIgez7MqNd5fu74R2UfcA.png" /><figcaption>The better flow starts before the prompt, with the context only you can provide.</figcaption></figure><h3>How I Actually Use AI</h3><p>I use AI constantly. I just do not use it the same way for every task.</p><p>For low-risk, mechanical work, I use it freely: syntax, documentation details, quick queries, boilerplate, repetitive refactors, spreadsheet cleanup, rough scripts, and turning messy notes into structure.</p><p>That kind of work used to steal time. Now it does not have to.</p><p>For exploratory work, I use AI as a thinking partner. I ask it to compare approaches, explain tradeoffs, challenge assumptions, or show me a few ways to frame the problem.</p><p>I am not asking it to choose for me. I am using it to see more angles.</p><p>For higher-risk work, I slow down.</p><p>Architecture decisions. Production behavior. Data correctness. Legacy constraints. Migration risk. Anything that can quietly break a system or affect the business.</p><h4>That is where I frame the problem first</h4><ul><li>What matters?</li><li>What cannot change?</li><li>What assumptions are dangerous?</li><li>Where has this system hurt us before?</li></ul><p>Then AI can help draft, organize, or pressure-test the solution.</p><p>But I stay close to the decision.</p><p><strong><em>The more risk a decision carries, the more context I bring to the tool.</em></strong></p><p>That is the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQbgeWTZdU1A81jRoV_kPw.png" /><figcaption>Ownership starts where automation stops.</figcaption></figure><p>That is the difference.</p><p>AI gives me more room to think. It clears the repetitive work faster, helps me explore options earlier, and lets me spend more energy on the parts where context matters.</p><p>The key is treating AI as a thought partner, not an oracle.</p><p>It can speed up the mechanical parts. It can sharpen the thinking when I engage with it properly. But it cannot own the context for me.</p><h3>You’re Not an Imposter</h3><p>The doubt you feel, that creeping sense that you did not really earn what you built, does not mean you are doing something wrong. It may mean you understand what engineering actually is.</p><p>Engineering was never just typing fast, remembering syntax, or suffering through boilerplate until the work felt earned. It is understanding the system well enough to know what matters, what can change, what cannot, what looks clean but creates risk, and what looks messy but exists for a reason.</p><p>That is the part AI does not automatically give you.</p><p>You could ask AI to generate the migration path, accept the first reasonable answer, and move faster. Sometimes that might even work. But when you slow down to understand the constraints, preserve the flows that matter, and define what “correct” means for your system, that is not wasted time.</p><p>That is the engineering.</p><p>AI does not make you less of an engineer because you use it. It just changes where the work shows up.</p><p>Less time fighting the blank page. Less time digging through syntax. Less time doing the repetitive parts by hand. More time understanding what matters, where to be careful, and what the tool needs to know before it can help.</p><p>That is the shift.</p><p>Use AI to move faster through the parts that do not need your full attention. Stay close to the parts that do.</p><blockquote>The risk isn’t that AI will replace you.</blockquote><blockquote>The risk is that you’ll let it.</blockquote><p>Not all at once. Not dramatically.</p><p>But slowly, in small moments where you stop questioning, stop framing, and stop owning the work.</p><p>The code may come faster now.</p><p><strong>But the ownership is still yours.</strong></p><p>Thanks for reading. If this resonated with you, I’d love to hear how you’re thinking about AI, engineering, and ownership in your own work.</p><p>Type less. Think harder.</p><p>If you’re interested in AI, data platforms, cloud engineering, and analytics, hit <a href="https://medium.com/@mahadeveaswar">follow</a> and feel free to add me on <a href="https://www.linkedin.com/in/mahadeveaswar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5dbb2d0016a" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/the-ai-imposter-syndrome-the-quiet-anxiety-of-building-with-ai-f5dbb2d0016a">The AI Imposter Syndrome: The Quiet Anxiety of Building With AI</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building RESTful APIs using Flask]]></title>
            <link>https://pub.towardsai.net/building-restful-apis-using-flask-8ba2716d361f?source=rss-354de2ec0117------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba2716d361f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Mahadev Easwar]]></dc:creator>
            <pubDate>Thu, 13 May 2021 16:01:14 GMT</pubDate>
            <atom:updated>2021-05-13T16:01:14.052Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/programming">Programming</a></h4><h4>Lightweight Web Framework in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0OwVytyiWBb896OCJ1fgg.png" /><figcaption><a href="https://github.com/pallets/flask/blob/master/artwork/logo-full.svg">Flask</a> <a href="https://www.pexels.com/">Framework</a></figcaption></figure><p><strong><em>What is an API?</em></strong></p><blockquote>An Application Programming Interface (API) is a software intermediary that allows two applications to communicate.</blockquote><p><strong><em>What is a web framework and why is it useful?</em></strong></p><p>A web framework is a software framework that is created to support the development of dynamic sites, web services, and web applications. A web framework is a code library that makes web development quicker and easier by giving basic patterns for building reliable, scalable, and maintainable web applications ¹.</p><p><strong><em>Flask: Introduction</em></strong></p><p><em>Flask</em><strong><em> </em></strong>is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around <em>Werkzeug </em>and <em>Jinja </em>and has become one of the most popular Python web application frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xzPzSwwNhnw6g9PflDj-5w.png" /><figcaption>No. of Package Downloads Last Month. <a href="https://pypistats.org/">Source</a>. ²</figcaption></figure><p><strong><em>Why is it a microframework?</em></strong></p><blockquote>“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible ³.</blockquote><p>Flask offers suggestions but doesn’t enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that makes adding new functionality easy ⁴.</p><p><strong><em>Why use Flask?</em></strong></p><ul><li>Easy to set up</li><li>Minimalistic</li><li>Flexible to add any extensions for more functionalities</li><li>Active community</li></ul><p>In this article, I will demonstrate how to set up, build and run a simple Flask application.</p><p><strong><em>Package Installation</em></strong></p><p>It is generally recommended to install packages in a virtual environment specific to the project.</p><pre># command prompt<br><strong>pip</strong> install Flask</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*iZSZuv6qH-GhmHGhSG1ucA.jpeg" /><figcaption>Installing Flask package</figcaption></figure><p><strong><em>JSON</em></strong></p><p>JSON is a generic data format with a minimal number of value types: strings, numbers, booleans, lists, objects, and null. Although the notation is a subset of JavaScript, these types are represented in all common programming languages, making JSON a good candidate to transmit data across language gaps ⁵.</p><pre># JSON Example:<br>{<br>&quot;id&quot; : 1,<br>&quot;name&quot; : &quot;john&quot;<br>&quot;age&quot; : &quot;25&quot;,<br>&quot;activities&quot; : [&quot;cricket&quot;,&quot;football&quot;],<br>&quot;class&quot; : [{&quot;year&quot;:&quot;2020&quot;,&quot;dept&quot;:&quot;CSE&quot;}]<br>}</pre><p><strong><em>Building a Flask App</em></strong></p><p>I will build a simple application using Flask that will access employee data and return the info requested in the input. We will send and receive the data both using <em>JSON </em>file format. Since I will be giving a data-based demonstration, I’m loading the <em>pandas</em> package too.</p><ol><li>Importing the required packages</li></ol><pre><strong>from </strong>flask <strong>import </strong>Flask, request, jsonify <br><strong>import</strong> pandas as pd</pre><p>The directory structure of the project would be as follows</p><pre>Demo/<br>| — emp_info.csv<br>| — emp_status.csv<br>| — app.py</pre><p>2. Creating an application instance</p><pre>app = Flask(__name__)</pre><p>3. Declaring the endpoint using .route() and accepted methods like POST, GET. By default, it just listens for GET method. Let us enable just the POST method for this API.</p><pre>@app.route(<strong>&quot;/get_emp_info&quot;</strong>, methods = [<strong>&#39;POST&#39;</strong>])</pre><p>4. Defining the functionality that the application will perform. Retrieving the employee data from CSV files based on the input data.</p><pre>@app.route(<strong>&quot;/get_emp_info&quot;</strong>, methods = [<strong>&#39;POST&#39;</strong>])<br><strong>def </strong>get_employee_record():<br>    input_data = json.loads(request.get_json())<br>    ids = input_data[<strong>&#39;</strong>emp_ids<strong>&#39;</strong>]<br>    status = input_data[<strong>&#39;</strong>status<strong>&#39;</strong>]<br>    emp_info = pd.read_csv(<strong>&#39;</strong>emp_info.csv<strong>&#39;</strong>)<br>    emp_status = pd.read_csv(<strong>&#39;</strong>emp_status.csv<strong>&#39;</strong>)<br>    emp_status = emp_status[(emp_status[<strong>&#39;</strong>emp_no<strong>&#39;</strong>].isin(ids)) &amp;     (emp_status[<strong>&#39;</strong>status<strong>&#39;</strong>].isin(status))]<br>    emp_info = emp_info[emp_info[<strong>&#39;</strong>emp_no<strong>&#39;</strong>].isin(emp_status[<strong>&#39;</strong>emp_no<strong>&#39;</strong>])]<br>    emp_info = pd.merge(emp_info,emp_status,on=<strong>&#39;</strong>emp_no<strong>&#39;</strong>,how=<strong>&#39;</strong>left<strong>&#39;</strong>)<br>    out_data = emp_info.to_dict(orient=<strong>&#39;</strong>records<strong>&#39;</strong>)<br>    <strong>return </strong>jsonify(out_data)</pre><p>The<strong><em> jsonify</em></strong><em>()</em> is a helper method provided by Flask to properly return <em>JSON </em>data. It returns a Response object with the application/json mimetype set.</p><p>5. Setting the Python application to run on the local development server. By default, the debug mode is <em>False</em>. To restart the service as and when code is modified, the debug mode can be set to <em>True.</em></p><pre><strong># </strong>Setting port number and host i.e., localhost by default<strong><br>if __name__</strong> == <strong>&quot;__main__&quot;</strong>:<br>    app.run(<strong>host</strong>=<strong>&#39;</strong>0.0.0.0<strong>&#39;</strong>, <strong>port</strong>=6123)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a86e43fb006bf94f1182c08843fdffec/href">https://medium.com/media/a86e43fb006bf94f1182c08843fdffec/href</a></iframe><p>6. Running the Python program on the local server</p><pre># command prompt<br><strong>python</strong> app.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbBkf2T8x6nKlNisydDozA.png" /><figcaption>Running the Python Application</figcaption></figure><p><strong><em>Testing the Application</em></strong></p><p>Using the <em>requests </em>package to send a POST request to the developed application.</p><pre># command prompt - installing requests package<br>$ <strong>pip</strong> install requests</pre><pre># Python code to test<strong><br>import </strong>requests, json<br># sample request<br>data = {&quot;emp_ids&quot;:[&quot;1001&quot;,&quot;1002&quot;,&quot;1003&quot;],&quot;status&quot;:[&quot;active&quot;]}<br># Hitting the API with a POST request<br>ot = requests.post(url=<strong>&#39;http://localhost:6123/get_emp_info&#39;</strong>, json=json.dumps(data))<br>print(ot.json())</pre><pre># Response JSON <br>[{<br> &#39;cmp&#39;: &#39;ABC&#39;,<br> &#39;emp_no&#39;: 1001,<br> &#39;name&#39;: &#39;Ben&#39;,<br> &#39;salary&#39;: 100000,<br> &#39;status&#39;: &#39;active&#39;<br>}, {<br> &#39;cmp&#39;: &#39;MNC&#39;,<br> &#39;emp_no&#39;: 1002,<br> &#39;name&#39;: &#39;Jon&#39;,<br> &#39;salary&#39;: 200000,<br> &#39;status&#39;: &#39;active&#39;<br>}]</pre><p><strong><em>Summary</em></strong></p><p>Concepts we’ve covered in this article:</p><ul><li>API &amp; Web framework</li><li>Flask Introduction</li><li>Setting up Flask environment</li><li>Building a Flask API</li><li>Testing the Flask API with a request using the <em>requests </em>package</li></ul><p>Flask is like the minimalist approach to building RESTful APIs.</p><blockquote>It is always the simple that produces the marvelous. — Amelia Barr</blockquote><p><strong><em>Wrapping Up</em></strong></p><p>Thanks to anyone who has made it this far. I hope you found this article helpful. Please share your feedback/queries in the comments. Now, it’s time for you to build your own APIs from scratch. Wish you luck!</p><p><em>If you found this article interesting and are passionate about Data Science, Data Engineering, or Software Engineering hit </em><a href="https://medium.com/@mahadeveaswar"><em>follow</em></a><em> and feel free to add me on </em><a href="https://www.linkedin.com/in/mahadeveaswar/"><em>LinkedIn</em></a><em>.</em></p><pre>REFERENCES:<br>1. <a href="https://www.goodfirms.co/glossary/web-framework/">https://www.goodfirms.co/glossary/web-framework/</a><br>2. <a href="https://pypistats.org/">https://pypistats.org/</a><br>3. <a href="https://flask.palletsprojects.com/">https://flask.palletsprojects.com/</a><br>4. <a href="https://github.com/pallets/flask">https://github.com/pallets/flask</a><br>5. <a href="https://www.infoworld.com/article/3222851/what-is-json-a-better-format-for-data-exchange.html">https://www.infoworld.com/article/3222851/what-is-json-a-better-format-for-data-exchange.html</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba2716d361f" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/building-restful-apis-using-flask-8ba2716d361f">Building RESTful APIs using Flask</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to SQL for Data Science]]></title>
            <link>https://pub.towardsai.net/a-complete-guide-to-sql-for-data-science-35743e73fd?source=rss-354de2ec0117------2</link>
            <guid isPermaLink="false">https://medium.com/p/35743e73fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Mahadev Easwar]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 01:01:20 GMT</pubDate>
            <atom:updated>2021-02-19T01:01:20.470Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-science">Data Science</a>, <a href="https://towardsai.net/p/category/tutorial">Tutorial</a></h4><h4>Querying Techniques Every Data Scientist Should Know</h4><p>Structured Query Language (SQL) is a language designed for storing, managing, and retrieving data from a relational database. All Relational DB Systems like MySQL, MS Access, SQL Server, Oracle, and Postgres use SQL as their standard database language for performing <strong>CRUD</strong> (Create, Read, Update &amp; Delete) operations. <br>Filtering and performing certain manipulations or computations at the Database level can significantly improve the performance of the application that utilizes the data. SQL is a language used by Data Scientists almost on a day-to-day basis but not spoken about as much as R or Python. Working knowledge of <strong>SQL </strong>and <strong>databases</strong> is imperative for <strong>Data Science</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhIJpxPgo_Tk3QVkAW_lGQ.png" /><figcaption><a href="http://pexels.com/">SQL Programming</a></figcaption></figure><p>A relational database has data points that are related to one another, organized into tables. Most of the RDBMS use similar syntax, with some notable differences. Some functions which are available in one could be named differently or not be available in the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*Z1PFtF_5cH4zqzZ3.png" /><figcaption>Stack Overflow Trends. <a href="https://www.datacamp.com/community/blog/sql-differences">Source</a>.</figcaption></figure><p><strong>MySQL</strong> has consistently been the most popular RDBMS according to the Stack Overflow trends. We’ll be using MySQL Workbench for demonstration purposes in this article.</p><p><em>*When using some of the commands explained below in another RDBMS, the results might vary.*</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*GwcMuE7UGRfidjZkUXjULg.png" /><figcaption><em>MySQL Workbench Interface</em></figcaption></figure><p><strong><em>Creating a Schema</em></strong></p><p>A<strong> Schema</strong> is a logical collection of database objects. It refers to the organization of data as a blueprint of how the database is constructed.²</p><p>A schema will be created only if no schema exists with the same name.</p><pre>Syntax: CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] <em>db_name ;</em></pre><pre>CREATE SCHEMA company_info;<br>use company_info;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*nT1YU9uws_6n5UtVnkq1eA.jpeg" /><figcaption>Schema created</figcaption></figure><p><strong><em>Creating a Table</em></strong></p><p><strong>Tables </strong>are<strong> </strong>database objects that contain data, logically organized in rows and columns, similar to a spreadsheet. Each row represents a record, and each column represents a field in the record.²</p><p>You can find the various data types<strong> </strong>and how to use them effectively in designing databases in the MySQL tutorial <a href="https://www.mysqltutorial.org/mysql-data-types.aspx/">documentation</a>. When creating tables we can apply certain constraints to the fields in the table. You can find the different MySQL constraints on the <a href="https://www.javatpoint.com/mysql-constraints">javatpoint</a> page.</p><pre><em>Syntax</em>: CREATE TABLE table_name (column_name column_type);</pre><pre># Sample query for creating industry_data table<br>CREATE TABLE industry_data (<br>cmp_id INT UNSIGNED PRIMARY KEY,<br>companyname VARCHAR(50) NOT NULL,<br>industry_type VARCHAR(50) NOT NULL,<br>industry_code VARCHAR(50) NOT NULL,<br>start_yr INT<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*knBq-Ilk2ZAkClMwmgE1hg.jpeg" /><figcaption>Tables created</figcaption></figure><p><strong><em>Viewing the Tables in the Schema</em></strong></p><pre>show tables; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*g3omxbL0SUsNbK_iZa8ZMA.jpeg" /><figcaption>Tables in the schema</figcaption></figure><p><strong><em>Viewing Table Description</em></strong></p><pre>desc cmp_details; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*RiNWNy9muJUF7B1hcq2Oxg.png" /><figcaption>cmp_details table description</figcaption></figure><p><strong><em>ALTER TABLE</em></strong></p><p>The ALTER TABLE the statement provides the option to add, delete or modify columns of an existing table.</p><pre>Syntax:<br># Addition of column &amp; Modification of column datatype<br>ALTER TABLE table_name ADD|MODIFY <em>column_name column_definition</em>;<br># Change column_name &amp; column_definition<br>ALTER TABLE table_name CHANGE COLUMN <em>old_name new_name column_definition</em>; <br># Drop column <br>ALTER TABLE table_name DROP COLUMN <em>column_name</em>;<br>desc dummy;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*D6vn_phiJrBM9d3Mms8QwA.jpeg" /><figcaption>dummy table description</figcaption></figure><pre># Adding new column comments<br>ALTER TABLE dummy<br>ADD comments_a varchar(50),<br>ADD comments_b varchar(50);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*58Pa34l9do_hKy3DSkVYBg.jpeg" /><figcaption>columns added</figcaption></figure><pre># Modify datatype of column address<br>ALTER TABLE dummy<br>MODIFY address TEXT;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*Zm0yr8USXYNWWORwF7asug.jpeg" /><figcaption>column datatype modified</figcaption></figure><pre># Dropping column<br>ALTER TABLE dummy <br>DROP comments_b;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*XC3KNR7ucID2P1yzFH60Ig.jpeg" /><figcaption>column dropped</figcaption></figure><pre># Changing column name &amp; datatype<br>ALTER TABLE dummy <br>CHANGE COLUMN comments_a address_line text;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*jGrOGaCMMb3ACfNFMyda7A.jpeg" /><figcaption>column modified</figcaption></figure><p><strong><em>DROP TABLE</em></strong></p><pre>Syntax: DROP TABLE table_name;</pre><pre>DROP TABLE dummy;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*iNJhKyaVRJ3y1W2fyKfDxw.jpeg" /><figcaption>tables in schema after drop</figcaption></figure><p><strong><em>Loading Data from a CSV</em></strong></p><p><strong><em>*Follow the steps (in the box) below with caution. Do not try these in your Database connection at the workplace.*</em></strong></p><pre>show global variables like &#39;local_infile&#39;;<br># If local_infile is not &#39;ON&#39; allow local file to be loaded<br>set global local_infile=true;<br># Edit the Connection settings - &#39;Advanced&#39; Tab<br>OPT_LOCAL_INFILE=1</pre><p><em>Prerequisite</em>: <em>A database table matching the structure of the file into which its content would be imported.</em></p><pre># Code to load the csv contents into a table<br># Sample query for loading industry_data from csv<br>LOAD DATA LOCAL INFILE &#39;C:/SQL/industry.csv&#39; <br>INTO TABLE industry_data <br>FIELDS TERMINATED BY &#39;,&#39; <br>ENCLOSED BY &#39;“&#39;<br>LINES TERMINATED BY &#39;\n&#39;<br>IGNORE 1 ROWS;</pre><p><strong><em>Reading Records</em></strong></p><p>SELECT is used to retrieve data selected from one or more tables and can include <em>UNION </em>statements and subqueries. <br>The <em>LIMIT </em>command restricts the number of records retrieved by the <em>SELECT </em>statement.</p><pre>SELECT * FROM company_info.cmp_details LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*hueKfrHeV-FtFsyIwN-rfQ.jpeg" /><figcaption>cmp_details table</figcaption></figure><pre>SELECT * FROM company_info.cmp_revenue LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*3BNfEXEnwe2TV7ibVc1MWQ.jpeg" /><figcaption>cmp_revenue table</figcaption></figure><pre>SELECT * FROM company_info.industry_data LIMIT 5; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*2ppgSJTRi2-la3xaehwMUw.jpeg" /><figcaption>industry_data table</figcaption></figure><pre>SELECT * FROM company_info.service_info LIMIT 10;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*IcvDR6PXKiTYfvpnbFjIyg.jpeg" /><figcaption>service_info table</figcaption></figure><p>SELECT service_station_id,active_status FROM company_info.service_info;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*9fBQ_-qzQ__uZGpvdczkYw.jpeg" /><figcaption>selecting columns</figcaption></figure><p><strong><em>Inserting a Record</em></strong></p><p>INSERT INTO statement is used to insert new records in a table. If you are entering values for all the columns of the table, you need not specify the column names in the query. However, the order of the values should be the same as the columns in the table.⁴</p><pre>Syntax: INSERT INTO table_name ( field1, field2,...fieldN )<br>        VALUES ( value1, value2,...valueN );</pre><pre>INSERT INTO company_info.cmp_revenue (id, address, founder, revenue)<br>VALUES (1055,&#39;130 Dummy Junction&#39;,&#39;Diana&#39;,&#39;$8.43B&#39;);<br>INSERT INTO company_info.cmp_revenue (id, address, founder, revenue)<br>VALUES (1060,&#39;150 Dummy Junction&#39;,&#39;Fiona&#39;,&#39;&#39;);</pre><pre>SELECT * FROM cmp_revenue where id in (&#39;1055&#39;,&#39;1060&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*-vYeU771FVzVOsVXNEQfcg.jpeg" /><figcaption>Newly inserted record</figcaption></figure><p>For updation/deletion of records, it is recommended we specify a unique column or primary key of the table in the where clause to prevent unintended records from getting modified.</p><p><strong><em>Updating Records</em></strong></p><p>The UPDATE statement is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using an UPDATE statement.⁷</p><pre>Syntax: UPDATE table_name SET field1 = new_value1, field2 = new_value2 [WHERE clause];</pre><pre>UPDATE company_info.cmp_revenue  <br>SET revenue = NULL<br>WHERE id in (&#39;1055&#39;,&#39;1060&#39;);</pre><pre>SELECT * FROM cmp_revenue where id in (&#39;1055&#39;,&#39;1060&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*pZnTUls-OdczjOu8SKV-Xg.jpeg" /><figcaption>Updated records</figcaption></figure><p><strong><em>Deleting Records</em></strong></p><p>The DELETE statement is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause.⁷</p><pre>Syntax: DELETE FROM table_name WHERE condition;</pre><pre>DELETE FROM cmp_revenue where id in (&#39;1055&#39;,&#39;1060&#39;);</pre><pre>SELECT * FROM cmp_revenue where id in (&#39;1055&#39;,&#39;1060&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*YNpF7US4bmS512m4IZSK9w.jpeg" /><figcaption>Records deleted</figcaption></figure><p><strong><em>Filtering Records</em></strong></p><p>The WHERE clause in MySQL is a keyword used to specify the criteria for retrieving records from the table. It always follows a SELECT, INSERT, UPDATE or DELETE statement to filter the records and perform various operations on the data.¹</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*XwvFnHdY1coZWNwz6Gwovg.jpeg" /><figcaption>Operations &amp; Description</figcaption></figure><p>Let us try these operations with SELECT statements using the tables we’ve created.</p><pre>Syntax: <br>SELECT select_list <br>FROM table_name <br>WHERE condition;</pre><pre>SELECT * FROM service_info WHERE cmp_id = &#39;1002&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*iR08owb0SQI72KHLSAx2hQ.jpeg" /><figcaption>operator =</figcaption></figure><pre>SELECT * FROM service_info WHERE cmp_id in (&#39;1001&#39;,&#39;1002&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*2Y4-TNbOo8TG1G11gZkFKA.jpeg" /><figcaption>operator in</figcaption></figure><pre>SELECT * FROM cmp_details WHERE headquarters not in (&#39;Hungary&#39;,&#39;Berlin&#39;,&#39;Banglore&#39;,&#39;California&#39;,&#39;New York&#39;,&#39;Berlin&#39;) LIMIT 10;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*a2i1TTzk-0jdQA2DKJyDvg.jpeg" /><figcaption>operator not in</figcaption></figure><pre>SELECT * FROM industry_data WHERE start_yr &gt; 2010;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*OI4x5HzMlcyoRYAZTzwyrA.jpeg" /><figcaption>operator &gt;</figcaption></figure><pre>SELECT * FROM industry_data WHERE start_yr &lt; 1980;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*5zL10b5RXwB0GdX7eVK-Ew.jpeg" /><figcaption>operator &lt;</figcaption></figure><pre>SELECT * FROM industry_data WHERE start_yr &lt;= 1985;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*5wskoKf9yqMx6zGQWpbBLg.jpeg" /><figcaption>operator &lt;=</figcaption></figure><pre>SELECT cmp_id,companyname,industry_type FROM industry_data WHERE start_yr &gt;= 2003;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*zyf0mOjUat0zCu_MMsD8hg.jpeg" /><figcaption>operator &gt;=</figcaption></figure><p>Both the operators below will perform the same operation. Checking for values where the parameter is not equal to the value in the condition.</p><pre># Not equal operation<br>SELECT DISTINCT start_yr FROM industry_data WHERE start_yr!= &#39;1979&#39;;<br>SELECT DISTINCT start_yr FROM industry_data WHERE start_yr&lt;&gt;&#39;1979&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/54/1*7X6OK2ObxMFgHDprPP6l8Q.jpeg" /><figcaption>operator &lt;&gt;</figcaption></figure><pre>SELECT * FROM industry_data <br>WHERE industry_type = &#39;Electronic Components&#39; <br>OR cmp_id in (&#39;1017&#39;,&#39;1021&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*6wfAInsIS7wCxrSIXsTKMg.jpeg" /><figcaption>OR operator</figcaption></figure><pre>SELECT * FROM industry_data <br>WHERE industry_type = &#39;Electronic Components&#39; <br>AND start_yr = &#39;1979&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*HmIQNbTguiSdOSLuO5hDPw.jpeg" /><figcaption>AND operator</figcaption></figure><p>The BETWEEN operator uses the greater than or equal and less than or equal operators.</p><pre>SELECT cmp_id,companyname,industry_type,start_yr <br>FROM industry_data<br>WHERE start_yr BETWEEN 1990 AND 2000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*U0oGvKtqGHnh81o2cUq2SQ.jpeg" /><figcaption>BETWEEN operator</figcaption></figure><pre>SELECT * FROM industry_data<br>WHERE industry_type LIKE &#39;oil%&#39;<br>OR industry_type LIKE &#39;%pharma%&#39;<br>OR industry_code LIKE &#39;%712&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*tZYs9zIDERmr_0IX-jGahA.jpeg" /><figcaption>LIKE operator</figcaption></figure><pre>SELECT * FROM cmp_revenue <br>WHERE revenue IS NULL;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Soy7k2DtGpnTNqooVSRpYg.jpeg" /><figcaption>IS NULL operator</figcaption></figure><pre>SELECT * FROM cmp_revenue <br>WHERE revenue IS NOT NULL<br>LIMIT 10;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*EneffGP9knBelJBlp46jyg.jpeg" /><figcaption>IS NOT NULL operator</figcaption></figure><p><strong><em>Arranging Data</em></strong></p><p>We can use the ORDER BY statement to arrange the records in ascending or descending order. By default, the records are arranged in ascending order if the preferred order is not mentioned.</p><pre>Syntax :<br>SELECT select_list FROM table_name <br>ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;</pre><pre>SELECT * FROM cmp_revenue ORDER BY founder ASC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*kus4wR3-TForPy8NBYJXIw.jpeg" /><figcaption>founder - order by ascending</figcaption></figure><pre>SELECT id,address,founder FROM cmp_revenue ORDER BY id DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*ieNHRp6Q4t112MYyoCHDaQ.jpeg" /><figcaption>id - order by descending</figcaption></figure><pre><strong>JOIN</strong> Syntax:<br>SELECT column_list FROM table_1 <br>[LEFT|RIGHT|INNER] JOIN table_2<br>ON join_condition;</pre><p><strong><em>LEFT JOIN</em></strong></p><p>The LEFT JOIN selects all the records from the left table regardless of whether matching rows exist in the right table. In case there are no matching rows from the right table, the columns of the right table in the final result set are filled with NULL for those records.³</p><p>We will now merge all the tables using the LEFT JOIN operation on the field cmp_id.</p><pre>SELECT * FROM (<br>SELECT A.cmp_id,company_url,id,founder, <br>revenue,companyname,industry_type, <br>service_station_id,active_status,service_station_owner <br>FROM cmp_details A<br>LEFT JOIN  cmp_revenue B<br>ON A.cmp_id=B.id<br>LEFT JOIN industry_data C<br>ON A.cmp_id=C.cmp_id<br>LEFT JOIN service_info D<br>ON A.cmp_id=D.cmp_id) T<br>WHERE cmp_id in (1017,1018,1019);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*0JZeRxGOLMb0z20s7txv9g.jpeg" /><figcaption>Left join</figcaption></figure><p>If you noticed, I have mentioned the table alias alongside the ‘cmp_id’ field in the SELECT query but haven’t specified it for the other columns, because there are 3 tables(cmp_details, industry_data, service_info) with the ‘cmp_id’ field. Not mentioning the table alias would cause ambiguity as to which table the ‘cmp_id’ should be derived from.</p><p><strong><em>INNER JOIN</em></strong></p><p>The INNER JOIN selects the records which are common to both the tables. In case there are no matching records from either one of the tables, the columns of both the tables in the final result set will be dropped for those records.⁵</p><pre>SELECT * FROM industry_data A<br>INNER JOIN cmp_revenue B<br>ON A.cmp_id=B.id<br>WHERE A.cmp_id BETWEEN 1015 AND 1020;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*hoD2Q9Nk2ADiTFM45mB-iA.jpeg" /><figcaption>Inner join</figcaption></figure><p>We can see the record for id ‘1018’ dropped since it is available in one table but not in the other.</p><p><strong><em>RIGHT JOIN</em></strong></p><p>The RIGHT JOIN returns all records from the RIGHT-side table specified in the ON condition and only those rows from the other table where the join condition matches.¹</p><pre>SELECT * FROM industry_data A<br>RIGHT JOIN service_info B<br>ON A.cmp_id=B.cmp_id<br>WHERE B.cmp_id BETWEEN 1050 AND 1052;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*_PcxRprBdSOnpemIMTia2w.jpeg" /><figcaption>Right join</figcaption></figure><p>Here we can observe how the records on the table from the right will not be dropped even if a corresponding record is not found on the left table.</p><p><strong><em>Aggregate Functions</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*UdBLF6IlG-vOy843K88mig.png" /><figcaption>Aggregate Functions</figcaption></figure><pre>SELECT COUNT(*) as total_companies, COUNT(DISTINCT start_yr) as unique_yrs,MIN(start_yr) as min_year, MAX(start_yr) as max_year, AVG(start_yr) as avg_start_yr<br>FROM industry_data;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*-xa9_kyIMPKqN0PUYqavng.jpeg" /><figcaption>count, distinct, min, max, avg</figcaption></figure><p><strong><em>GROUP BY</em></strong></p><p>The GROUP BY clause is used to collect data from multiple records and group the result by one or more columns. You can also use aggregate functions like COUNT, SUM, MIN, MAX, AVG, etc. on the grouped column.³</p><pre>Syntax:<br>SELECT c1, c2,..., cn, aggregate_function(ci) <br>FROM table <br>WHERE conditions <br>GROUP BY c1 , c2,...,cn;</pre><p>Let us now find the average starting year for a set of industry types.</p><p><strong><em>GROUP BY &amp;</em></strong> <strong><em>AVG</em></strong></p><pre>SELECT industry_type, AVG(start_yr) FROM industry_data<br>WHERE industry_type in (&#39;Natural Gas Distribution&#39;,&#39;Hotels/Resorts&#39;,&#39;Major Banks&#39;,&#39;EDP Services&#39;)<br>GROUP BY industry_type;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*bENHyfyiiekZTQc_vNV8eA.jpeg" /><figcaption>average start year for industry type</figcaption></figure><p>Finding the count of service stations that are active and inactive.</p><p><strong><em>GROUP BY &amp;</em></strong> <strong><em>COUNT</em></strong></p><pre>SELECT count(*),active_status FROM service_info<br>GROUP BY active_status;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*f2pdcyNWo5j3qMIKlK27FQ.jpeg" /></figure><p><strong><em>HAVING</em></strong></p><p>The HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates. The HAVING clause is often used with the GROUP BY clause to filter groups based on a specific condition. If the GROUP BY clause is omitted, the HAVING clause behaves like the WHERE clause.¹</p><pre>Syntax:<br>SELECT select_list FROM table_name <br>WHERE search_condition <br>GROUP BY group_by_expression <br>HAVING group_condition;</pre><p>Let’s say we need to find the company ids that have more than 3 active service stations.</p><pre>SELECT cmp_id,count(cmp_id),active_status FROM service_info<br>GROUP BY cmp_id,active_status<br>HAVING count(cmp_id) &gt; 3 and active_status = 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*sf-kauivHk3EaoO5SvUILg.jpeg" /><figcaption>having</figcaption></figure><p><strong><em>String Functions</em></strong></p><p>You can find below the table containing all the essential string functions in MySQL. For examples, please refer to the <a href="https://www.w3resource.com/mysql/string-functions/mysql-trim-function.php">w3resource</a> link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*zILtagHIQToaMz9dfuPqNQ.png" /><figcaption>Important String Functions</figcaption></figure><p><strong><em>UNION</em></strong></p><p>The UNION operator allows us to combine two or more result sets of queries into a single result set. By default, the UNION operator removes duplicate rows even if the DISTINCT operator is not mentioned explicitly.¹</p><pre>Syntax:<br>SELECT column_list <br>UNION [DISTINCT | ALL] <br>SELECT column_list <br>UNION [DISTINCT | ALL] <br>SELECT column_list ...</pre><pre>SELECT * FROM cmp_details WHERE cmp_id in (1011,1013)<br>UNION<br>SELECT * FROM cmp_details WHERE cmp_id BETWEEN 1012 AND 1017<br>ORDER BY headquarters ASC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*qAzysrrHpgVnz-HnwcQauQ.jpeg" /><figcaption>union by default distinct</figcaption></figure><pre>SELECT * FROM cmp_details WHERE cmp_id in (1011,1013)<br>UNION ALL<br>SELECT * FROM cmp_details WHERE cmp_id BETWEEN 1012 AND 1017<br>ORDER BY cmp_id ASC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*qLwmAOkHP_kXHRBDCWLrSw.jpeg" /><figcaption>union all</figcaption></figure><p><strong><em>CASE</em></strong></p><p>The CASE expression is a control flow structure that allows us to add if-else logic to a query.¹</p><pre>#Simple CASE<br>Syntax:<br>CASE value    <br>WHEN value1 THEN result1    <br>WHEN value2 THEN result2    <br>…    <br>[ELSE else_result] <br>END</pre><pre>#Searched CASE expression<br>Syntax:<br>CASE    <br>WHEN expression1 THEN result1    <br>WHEN expression2 THEN result2    <br>…    <br>[ELSE else_result] <br>END</pre><p>Based on the start year range, set a time_period value based on conditions.</p><pre>SELECT DISTINCT start_yr,<br>CASE <br> WHEN start_yr &lt;= 2000 THEN &#39;OLD&#39;<br> WHEN start_yr &gt; 2000 AND start_yr &lt; 2010 THEN &#39;MEDIUM&#39;<br> WHEN start_yr &gt; 2010 THEN &#39;NEW&#39;<br> end as time_period<br>FROM<br> industry_data;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*_ol3KgWixp4zBjCqpvADRw.jpeg" /><figcaption>case condition</figcaption></figure><p><strong><em>Subquery</em></strong></p><p>A subquery is a query nested within another query. Also, a subquery can be nested inside another subquery.¹</p><p>Display company revenue details for companies that started after 2005.</p><pre>SELECT * FROM cmp_revenue<br>WHERE id in (<br>SELECT cmp_id FROM industry_data<br>WHERE start_yr &gt; 2005<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*oMl3F2rRuTauOfln6IjDXA.jpeg" /><figcaption>subquery</figcaption></figure><p><strong><em>WITH </em></strong><em>- Common Table Expression</em></p><p>WITH clause is used to define common table expressions. A common table expression is a named temporary result set.</p><pre>Syntax:<br>WITH cte_name (column_list) AS (<br>query<br>)<br>SELECT * FROM cte_name;</pre><p>Unlike a derived table, a CTE can be self-referencing (a <a href="https://www.mysqltutorial.org/mysql-recursive-cte/">recursive CTE</a>) or can be referenced multiple times in the same query. A CTE provides better readability and performance in comparison with a derived table.¹</p><pre>WITH companies AS (<br>SELECT companyname,industry_type,<br>CASE <br> WHEN industry_type=&#39;Natural Gas Distribution&#39; THEN 1<br>    WHEN industry_type=&#39;Major Pharmaceuticals&#39; THEN 2<br>    ELSE 0<br>END AS indus_category<br>FROM industry_data<br>WHERE start_yr &gt; 2005<br>) SELECT companyname <br>FROM companies<br>WHERE indus_category &gt; 0;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*6tG8Ji4E-WfO3dScjGwSfg.jpeg" /><figcaption>WITH CTE</figcaption></figure><p><strong><em>Summary</em></strong></p><p>Concepts we’ve covered in this article:</p><ul><li>Creating Schema and Tables</li><li>Alter, Drop Table — <em>(</em>ALTER TABLE,DROP TABLE<em>)</em></li><li>Loading Data from a CSV</li><li><strong>CRUD</strong><em> </em>Operations — <em>(</em>INSERT INTO,SELECT,UPDATE,DELETE<em>)</em></li><li>Filtering Records — <em>(</em>WHERE<em>)</em></li><li>Arranging Data — <em>(</em>ORDER BY<em>)</em></li><li>Joins — <em>(</em>INNER,LEFT,RIGHT<em>)</em></li><li>Aggregate Functions — <em>(</em>SUM,DISTINCT,COUNT,AVG,MIN,MAX,GROUP BY,HAVING<em>)</em></li><li>String Functions</li><li><em>UNION, </em>Subquery, Common Table Expression (WITH)</li></ul><blockquote>SQL, Lisp, and Haskell are the only programming languages that I’ve seen where one spends more time thinking than typing. - Philip Greenspun</blockquote><p><strong><em>Wrapping up</em></strong></p><p>Thanks to anyone who has made it this far. I hope you found this article helpful. Please share your feedback/queries in the comments. Now, it’s time for you to put your SQL skills to use. Type less, think hard! Wish you luck!</p><p><em>If you found this article interesting and are passionate about Data Science/Machine Learning, hit </em><a href="https://medium.com/@mahadeveaswar"><em>follow</em></a><em> and feel free to add me on </em><a href="https://www.linkedin.com/in/mahadev-easwar/"><em>LinkedIn</em></a><em>.</em></p><pre>REFERENCES:<br>1. <a href="http://www.mysqltutorial.org/">www.mysqltutorial.org</a><br>2. <a href="https://dev.mysql.com/doc/refman/8.0/en/">https://dev.mysql.com/doc/refman/8.0/en/</a><br>3. <a href="https://www.javatpoint.com/">https://www.javatpoint.com/</a><br>4. <a href="https://www.w3schools.com/sql/">https://www.w3schools.com/sql/</a><br>5. <a href="https://www.tutorialspoint.com/mysql/">https://www.tutorialspoint.com/mysql/</a><br>6. <a href="https://www.w3resource.com/mysql/mysql-tutorials.php">https://www.w3resource.com/mysql/mysql-tutorials.php</a><br>7. <a href="https://www.geeksforgeeks.org/sql-tutorial/">https://www.geeksforgeeks.org/sql-tutorial/</a></pre><p><strong><em>Suggestions</em></strong></p><p><a href="https://towardsdatascience.com/essential-sql-skills-for-data-scientists-in-2021-8eb14a38b97f">Essential SQL Skills for Data Scientists in 2021</a> by <a href="https://medium.com/u/4e1d06dd743">Leihua Ye, Ph.D.</a></p><p><a href="https://towardsdatascience.com/4-tricky-sql-questions-for-data-scientists-in-2021-88ff6e456c77">4 Tricky SQL Questions for Data Scientists in 2021</a> by <a href="https://medium.com/u/4e1d06dd743">Leihua Ye, Ph.D.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35743e73fd" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/a-complete-guide-to-sql-for-data-science-35743e73fd">A Complete Guide to SQL for Data Science</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Data Wrangling Skills for Data Scientists in 2021]]></title>
            <link>https://medium.com/data-science/essential-data-wrangling-skills-for-data-scientists-in-2021-87a5cb698287?source=rss-354de2ec0117------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a5cb698287</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mahadev Easwar]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 13:19:13 GMT</pubDate>
            <atom:updated>2021-01-05T13:19:13.710Z</atom:updated>
            <content:encoded><![CDATA[<h4>The most essential skill for Data Science — Data Wrangling with Pandas</h4><h4>A Complete Guide to Data Wrangling using Pandas (Python) library</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iISxO6ghX_V7SwJBTFMhCA.png" /><figcaption>Photo by <a href="https://www.pexels.com/@fauxels?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">fauxels</a> from <a href="https://www.pexels.com/photo/photo-of-person-holding-mobile-phone-3183153/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a>, edited with permission by the author</figcaption></figure><p><strong><em>Pandas</em></strong> is one of the core components of the Data Science toolkit. Over the past year, importing the Pandas library has become the primary step to every project that I’ve worked on, in Python. Loading and analyzing relational/labeled data has never been easier. As you can infer from the graph below, Pandas is only the second-highest downloaded Data Science package, after NumPy. It is understandable since Pandas was built on top of NumPy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*-y_rW5CHy9WoGQ59zl_10A.png" /><figcaption>No. of Package Downloads Last Month. <a href="https://pypistats.org/">Source</a>.¹</figcaption></figure><blockquote>Data Scientists spend 80% of their time preparing and managing data for analysis.</blockquote><p>In this article, I will demonstrate how to <em>Load, Explore, and Manipulate Data using Pandas</em>. Please find the data set used for the demonstration on <a href="https://github.com/mwaskom/seaborn-data/blob/master/mpg.csv">Github</a>. To acquire the skills and understand the concepts you’d be learning, I strongly recommend that you parallelly try executing the commands we will be covering in this article.</p><p>I will elaborate on the functionality of most of the commands, but if you want to brush up on the basics of Python, I recommend that you read the article below.</p><p><a href="https://link.medium.com/BhKOU360jcb">Introduction to Data Structures in Python</a></p><pre># installing pandas package<br>pip install pandas<br># importing the pandas library<br>import pandas as pd</pre><p><strong><em>What is a DataFrame?</em></strong></p><blockquote>The DataFrame is the primary Pandas Data Structure used to represent Data in a Tabular format.</blockquote><p>Let us <strong><em>load </em></strong>the mpg data into a DataFrame(DF) object using the Pandas <strong><em>read_csv()</em></strong> function.</p><pre>import pandas as pd<br># Loading the mpg data set from a local .csv file using Pandas<br>mpg_df = pd.read_csv(&#39;data/mpg_dataset.csv&#39;)<br># Print first 5 rows of the data<br>mpg_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*SYcv0lu2q0mAnk4-laBLzQ.png" /><figcaption>First 5 rows of the DataFrame</figcaption></figure><p>With the index and column headers, the DataFrame looks very much like an Excel table doesn’t it? Now let’s <strong><em>explore</em> </strong>the data.</p><h4>Exploration</h4><pre># Viewing the columns in the DataFrame<br>mpg_df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*uVnoPW04CSMfqRZW2iiSBg.png" /><figcaption>columns in the mpg data set</figcaption></figure><pre># dimensions of the DF<br>mpg_df.shape<br>&gt;&gt;&gt; (398, 9)<br>#Summary of the DF <br>mpg_df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*fHCVEH5pYEHkWNjK5I1YZg.png" /><figcaption>Summary of the mpg_df</figcaption></figure><pre># Viewing the data type of each column in the DF<br>mpg_df.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*MaBy1K9bemR1-B1-RplCIw.png" /><figcaption>data type of each column</figcaption></figure><p>The <strong>describe</strong> function in pandas can get you a quick summary of the data present in each field of the DF. This includes details like percentile, mean, standard deviation, etc. by default. When an object type field is described, details like count, number of unique values, mode, and frequency are returned.</p><pre># Summary of all numeric fields in DF by default<br>mpg_df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*Gf-9-S6e-uOisvu0IlfxAA.png" /><figcaption>summary of mpg_df</figcaption></figure><pre># Accessing a column from the DataFrame<br>mpg_df.mpg<br>mpg_df[&#39;mpg&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*av2tUk2IdoBPDBQgghI5rw.png" /><figcaption>column mpg from the data set</figcaption></figure><p>I suppose there are 3 things on your mind now. Let me guess.</p><ol><li>Why are we executing 2 commands in the same cell?</li><li>Why is the result not in the form of a table?</li><li>If I want the selected column in the tabular format, what should I do?</li></ol><p>The answer to the respective questions are :</p><ol><li>Both the commands that I’ve placed in the above cell for accessing the column, returns the same result</li><li>The result is not in the form of a table because the command does not return a DataFrame but a <strong><em>Series</em></strong></li><li>Use double square brackets while accessing the columns from a DF to get the result as a DF (tabular format)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*bSJi7zXip0P9eQ4UajdFqw.png" /><figcaption>mpg column series</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*RMs0GBUuLkZYhGNgIM_DbA.png" /><figcaption>mpg column as DF</figcaption></figure><p><em>If those weren’t the questions you had in mind, you can always leave a comment and I’ll get back to you.</em></p><p><strong><em>What is a Series?</em></strong></p><blockquote><em>Series</em> is a one-dimensional labeled array capable of holding data of any type. It has an index associated with each element. Essentially, a Series is just a column from an Table.</blockquote><p>Now that we have understood Series, we have a variety of functions specifically to understand more about the data in a particular column. Let us resume exploring the data.</p><pre># Describe of origin field in mpg_df<br>mpg_df.origin.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*0FslBjB_Ga-oPNLCUefMTA.png" /><figcaption>summary of ‘origin’ field in mpg_df</figcaption></figure><p>Interpreting the summary above : <br>count - total 398 values in the column, unique - 3 distinct values,<br>top - ‘usa’ is the mode of the column, freq - 249 is the frequency of the mode</p><pre># Values present in the column &amp; their occurence<br>mpg_df.origin.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*hBVXuc15fyzTvha9MsHYYw.png" /><figcaption>value_counts of origin</figcaption></figure><pre># check all the columns if there are any missing values mpg_df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*NAyQRlsmRF1jh5ILldXHWA.png" /><figcaption>columns with missing value count</figcaption></figure><pre># Assigning the df to another<br>cdf = mpg_df<br>cdf.head()</pre><p>Here the ‘=’ symbol does not create a new DF named ‘cdf’ from the mpg_df. Meaning, any modifications I make to the mpg_df/cdf will affect the other, as they’ll both share the same memory address.</p><pre>id(cdf)==id(mpg_df)<br>&gt;&gt;&gt; True</pre><p>So if you want to create a copy of the DF, use the <strong>copy()</strong> function.</p><pre>cdf = mpg_df.copy()<br>id(cdf)==id(mpg_df)<br>&gt;&gt;&gt; False</pre><h4>Manipulation</h4><p>We have so far covered the sections - <strong><em>loading </em></strong>and <strong><em>exploring</em></strong> the data. We’ll now learn how to <strong><em>manipulate </em></strong>the data.</p><p><strong><em>Slicing &amp; Dicing</em></strong></p><p>Basically, there are 3 ways of slicing a DF :</p><ul><li>square bracket - subsetting</li><li>loc - label based indexing</li><li>iloc - positional indexing</li></ul><p>Another option <strong>ix </strong>is like a blend of<strong> loc </strong>&amp; <strong>iloc</strong>. But we will not be covering that, as it is deprecated.</p><p>First, let’s explore the <strong><em>square bracket </em></strong>way of doing it.</p><pre># Select the row where mpg value is minimum<br>cdf[cdf[&#39;mpg&#39;]==cdf[&#39;mpg&#39;].min()] </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*b7DKIq5VXhPCi-jB30JS-w.png" /><figcaption>row with minimum mpg</figcaption></figure><p>If you want selected columns out of it, it is again another square bracket with the column names.</p><pre>cdf[[&#39;mpg&#39;,&#39;horsepower&#39;,&#39;origin&#39;]][cdf[&#39;mpg&#39;]==cdf[&#39;mpg&#39;].min()]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*_gJjOsXXvDVsvrZv92ziCA.png" /><figcaption>selected columns from the row with minimum mpg</figcaption></figure><p>Let’s say we want to set some value based on this condition. We can do it, but remember this will throw a warning and isn’t the recommended way.</p><pre>cdf[&#39;mpg&#39;][cdf[&#39;mpg&#39;]==cdf[&#39;mpg&#39;].min()] = 9.001 </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*nA1gx9dtYPfRpd1M1k-SAg.png" /><figcaption>warning message while setting value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*2dACZbHzmSiEmCDc8wlseg.png" /><figcaption>mpg min value set as 9.001 using []</figcaption></figure><p>The recommended approach to this is the use of <strong><em>loc </em></strong>property.</p><pre># Setting mpg value based on condition using loc<br>cdf.loc[cdf[&#39;mpg&#39;]==cdf[&#39;mpg&#39;].min(),&#39;mpg&#39;] = 9.005</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*uQ5N9J96EV6FMyETvEJeZQ.png" /><figcaption>min mpg value row set using loc</figcaption></figure><pre># If you want to modify multiple values based on a condition<br>cdf.loc[cdf[&#39;mpg&#39;]==cdf[&#39;mpg&#39;].min(),[&#39;mpg&#39;,&#39;weight&#39;,&#39;name&#39;]] = 9.005,4733,&#39;fordtorino&#39;<br>cdf.loc[cdf[&#39;mpg&#39;]==cdf[&#39;mpg&#39;].min()]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*oR6w80UDfS4LDAzF2cdUSw.png" /><figcaption>multiple values set based on loc condition</figcaption></figure><p>Yes, I used the loc condition even in the second command while accessing the row with a minimum ‘mpg’ value. You can access it, either way, using square brackets or loc. But for modifying values in the DF, the recommended approach is using <em>loc</em>.</p><p>You can also specify selected columns and indexes that you want to extract from the data as follows:</p><pre># Select first 5 indexes from column mpg to displacement<br>cdf.loc[0:5,&#39;mpg&#39;:&#39;displacement&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*vJ0ZpdXskAYXqDHbBSyaRg.png" /><figcaption>index 0 to 5 columns mpg to displacement</figcaption></figure><pre># Select first 5 indexes from column mpg to displacement<br>cdf.loc[[1,3,5],[&#39;mpg&#39;,&#39;displacement&#39;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*4abMeyV9Ifkvlw9fPq6Vow.png" /><figcaption>selected index &amp; cols using loc</figcaption></figure><p><strong><em>iloc </em></strong>can be used to extract rows based on an imaginary index position assigned to each row of the DF starting from 0 to (number of rows-1).</p><pre># Accessing row using index<br>cdf.iloc[[28]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*trggMLGRciNys-ZcvymFNg.png" /><figcaption>row index 28 using iloc</figcaption></figure><pre># Accessing the series based on index using iloc<br>cdf.iloc[28]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*6KgmlOg2icRJadWCwE1Afg.png" /><figcaption>series of index 28</figcaption></figure><pre># Accessing row,column based on index using iloc<br>cdf.iloc[28][&#39;weight&#39;]<br>cdf.iloc[28,4]<br>&gt;&gt;&gt; 4733</pre><p>While the first command accesses the ‘weight’ explicitly, specifying the field name, the second command points to the column index 4 (weight) to obtain the value.</p><p><em>Please follow the DF names carefully for the below section as there will be multiple DFs involved.</em></p><p><strong><em>Set index</em></strong></p><p><strong><em>set_index()</em></strong> function helps set the DF index (row labels) using one or more existing columns. There is an argument ‘<em>inplace’ </em>which is by default set to False. It can be set to True if the command should not return the resultant DF and instead make the change in the calling DF directly.</p><pre>abc_df = cdf.set_index(&quot;name&quot;)<br>abc_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Rqu-wEz6anL26LCqLHEo6g.png" /><figcaption>creating DF abc from cdf with name as index</figcaption></figure><p><strong><em>loc </em></strong>plays an important role in accessing rows using an index based on the label.</p><pre>abc_df.loc[&#39;buick skylark 320&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*QfXiNVxTgKjkMGFaCSl2tQ.png" /><figcaption>label based selection using loc</figcaption></figure><p><strong><em>Reset index</em></strong></p><p>We have the abc_df containing the column name as the index. To understand how reset_index works, I’ll subset rows from ‘cdf’ to a new DF named ‘rdf’.</p><pre>rdf = cdf.loc[cdf[&#39;mpg&#39;]&gt;17]<br>rdf.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*snrHteCLK1hyaPX-WwRiCA.png" /><figcaption>rdf subset DF where mpg&gt;17</figcaption></figure><p>To remove the index and reset the DF index back to the default numeric index or reset the existing numeric index from 0 to (number of rows-1), we use the <strong><em>reset_index()</em></strong> function.</p><pre># inplace=True makes the changes directly in rdf<br>rdf.reset_index(inplace=True)<br>rdf.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*xGYLbClO53Lic_q08e6OQQ.png" /><figcaption>rdf index reset</figcaption></figure><p>You can see the initial index value in the new column ‘index’. You can drop that by setting the argument <strong><em>drop </em></strong>to True. For instance, in the abc_df which currently has the name as the index, let’s reset the index with the drop argument set to True.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Rqu-wEz6anL26LCqLHEo6g.png" /><figcaption>abc_df with name as index</figcaption></figure><pre>abc_df.reset_index(inplace=True,drop=True)<br>abc_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*Y9l0fFcPIgICKnQso5iKSA.png" /><figcaption>abc_df index reset - name drop</figcaption></figure><p><strong><em>Creating a new column</em></strong></p><p>A new column can be created only if the length of the values matches the length of the index, or if a single value is set across the DF column.</p><pre># Creating a column name set to &#39;xxx&#39;<br>abc_df[&#39;name&#39;] = &#39;xxx&#39;</pre><pre># Creating a column based on existing columns<br>abc_df[&#39;calc&#39;] = abc_df[&#39;cylinders&#39;]*abc_df[&#39;mpg&#39;]<br>abc_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*cp0k6XmxTAoV9hqsPo_AbA.png" /><figcaption>new columns added - name, calc</figcaption></figure><p><strong><em>Dropping a column</em></strong></p><p>One or more columns from a DF can be dropped using the <strong><em>drop()</em></strong> function. Or for dropping a single column you can also use the <strong><em>del()</em></strong> function.</p><pre># Drop a single column - index<br>del(rdf[&#39;index&#39;])<br># Drop multiple columns<br>rdf = rdf.drop(columns=[&#39;displacement&#39;,&#39;weight&#39;])<br>rdf.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*iWnfyNHh3973UlAhCL6mbw.png" /><figcaption>columns dropped from rdf</figcaption></figure><p><strong><em>Renaming a column</em></strong></p><p>For renaming one or more columns of a DF use the <strong><em>rename()</em></strong> function.</p><pre># Renaming the columns of DF<br>rdf = rdf.rename(columns={<br>    &#39;acceleration&#39;:&#39;acc&#39;,<br>    &#39;model_year&#39;:&#39;year&#39;<br>})<br>rdf.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*8qaeiTgND1ObQJDalOSJoA.png" /><figcaption>columns renamed</figcaption></figure><p><strong><em>Sorting by column</em></strong></p><p>To sort a DF based on a column use the <strong><em>sort_values()</em></strong> function. By default, the ascending argument is True. If set to False, the DF will be in descending order.</p><pre>weight_sorted_df = mpg_df.sort_values(by=[&#39;weight&#39;],ascending=False)<br>weight_sorted_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*h_nNb6SV4KMVWs4BgnkjCg.png" /><figcaption>DF sorted by weight in desc order</figcaption></figure><p><strong><em>Performing String operations</em></strong></p><p>String operations that I find very helpful and most commonly used :</p><ul><li>strip() to trim whitespaces</li><li>upper() to capitalize</li><li>lower() for lowercase</li><li>contains() to check the presence of a string</li></ul><pre># String operations<br># Trimming whitespaces and making origin capital<br>kdf = mpg_df.copy()<br>kdf[&#39;origin&#39;] = kdf[&#39;origin&#39;].str.strip()<br>kdf[&#39;origin&#39;] = kdf[&#39;origin&#39;].str.upper()<br>kdf.origin.unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*Dv8CZQrxBCXgRX-DIueSig.png" /><figcaption>unique values after string operations</figcaption></figure><pre># Rows where origin contains string &#39;eur&#39; irrespective of the case<br>kdf[kdf[&#39;origin&#39;].str.contains(&#39;eur&#39;,case=False)].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*fz0X2xP0oVRwBCY5XQutHQ.png" /><figcaption>str ‘eur’ in origin</figcaption></figure><p>For more information on string manipulation techniques refer to <a href="https://www.geeksforgeeks.org/string-manipulations-in-pandas-dataframe/">Geeksforgeeks</a>.</p><p><strong><em>Creating a DataFrame</em></strong></p><pre># Creating a DF using a dictionary with list of prices &amp; country<br>price_dict = {&#39;country&#39;: [&#39;usa&#39;,&#39;japan&#39;,&#39;europe&#39;],<br>              &#39;price&#39;: [50000,85000,45000]}<br>price_df = pd.DataFrame(price_dict)<br>print(price_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*vy7lpTXSW1SHgVWshZd_wQ.png" /><figcaption>created price DF</figcaption></figure><p>There are many ways of creating a DF. I have mentioned just one of them. To check out all the different ways of creating a DF, refer to <a href="https://www.geeksforgeeks.org/different-ways-to-create-pandas-dataframe/">Geeksforgeeks</a>.</p><p><strong><em>Append to a DataFrame</em></strong></p><p><strong><em>append() </em></strong>function can be used to append rows to the end of the DF object. The argument ‘ignore_index’ is by default False, meaning the index of the DF appended will remain as it was before appending.</p><p>Consider a new DF named ‘pk’ as shown below, appended to the mpg_df</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*7wFW3DLs_ZNbveopwNNGZQ.png" /><figcaption>new DF ‘pk’ to append</figcaption></figure><pre>mpg_df.append(pk)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*9e07DKRrZg7qOHZ4B0I_ug.png" /><figcaption>new DF appended to the mpg_df</figcaption></figure><pre>mpg_df.append(pk,ignore_index=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*00UAdpum0gmz3kPYz6gDfA.png" /><figcaption>ignore index when appending new DF</figcaption></figure><p><strong><em>Concatenating DataFrames</em></strong></p><p>Concatenation of rows or columns with the existing DF can be performed using the <strong><em>concat()</em></strong> function. ‘axis’ argument decides the axis to concatenate along. axis 0 — index (default), 1- column.</p><pre># Concatenating the new DF pk and mpg_df<br>pd.concat([pk,mpg_df],ignore_index=True) # axis 0 by default</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*qWF2j6KkBPxdzQVeptNXpw.png" /><figcaption>concatenating ‘pk’ &amp; mpg_df</figcaption></figure><p>Similarly concatenating using axis=1 will create new columns to the right of the existing DF.</p><p><strong><em>Filling missing NA values</em></strong></p><p><strong><em>fillna()</em></strong> function can be used to fill all the NaN or NULL (missing) values present in a DF.</p><pre># Filling the mpg_df missing country price values with 0<br>mpg_df[&#39;price&#39;] = mpg_df[&#39;price&#39;].fillna(0)</pre><pre># Or filling missing values in multiple numeric columns in DF<br>mpg_df[[&#39;price&#39;,&#39;horsepower&#39;]] = mpg_df[[&#39;price&#39;,&#39;horsepower&#39;]].fillna(0)</pre><pre># For filling entire DF missing values with &#39;Missing&#39;<br>mpg_df = mpg_df.fillna(&#39;Missing&#39;)</pre><p><strong><em>Dropping row/column with missing values</em></strong></p><p><strong><em>dropna()</em></strong> function can be used to drop the row/column with missing values.</p><pre># Dropping rows with any missing values<br>tmp_df = mpg_df.dropna(axis=0,how=’any’,subset=None,inplace=False)</pre><pre>&#39;&#39;&#39;Dropping columns inplace with all values missing. subset checks dropna only for the mentioned columns&#39;&#39;&#39;</pre><pre>mpg_df.dropna(axis=1,how=’all’,subset = [’mpg’,’price’,’origin’],inplace=True)</pre><h4>Solve a Problem Time</h4><p>Let’s say we have to set a ‘price’ attribute based on each origin country. There are many ways that it can be done and I’m going to show you how.</p><ol><li>for loop</li><li>apply</li><li>merge</li><li>loc</li><li>mapping</li></ol><p><strong><em>for loop</em></strong></p><pre>for i in cdf[&#39;origin&#39;]:<br>    if i == &#39;usa&#39;:<br>        cdf[&#39;price&#39;] = 50000<br>    elif i == &#39;japan&#39;:<br>        cdf[&#39;price&#39;] = 85000<br>    elif i == &#39;europe&#39;:<br>        cdf[&#39;price&#39;] = 45000</pre><p><strong><em>apply</em></strong></p><p>Calling a function over <em>apply() </em>on a DF will perform that calculation for all rows/columns. Considered to be faster than for loops when complex operations are involved.</p><pre># Function defined to calculate the price<br>def calc_price(df):<br>    if df[&#39;origin&#39;] == &#39;usa&#39;:<br>        df[&#39;price&#39;] = 50000<br>    elif df[&#39;origin&#39;] == &#39;japan&#39;:<br>        df[&#39;price&#39;] = 85000<br>    elif df[&#39;origin&#39;] == &#39;europe&#39;:<br>        df[&#39;price&#39;] = 45000<br>    return df<br>weight_sorted_df = weight_sorted_df.apply(calc_price,axis=1)</pre><p><strong><em>merge</em></strong></p><p>Merging DFs is one of the most important functionality while working with data. Pandas support all database join operations that can be performed between DataFrame objects based on columns or indexes. This is what a <strong><em>merge() </em></strong>function looks like by default.</p><pre>pd.merge(left, right, how=&#39;inner&#39;, on=None, left_on=None, right_on=None)</pre><ul><li>‘left’ and ‘right’ refer to the DF objects</li><li>‘on’ refers to the columns list if both the DFs have common columns</li><li>If we do not have common columns we use ‘left_on’ and ‘right_on’ to specify the column names specific to the DF object</li><li>‘how’ refers to the join operation - (left, right, inner, outer)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*7HcyyZD2QHVseowU0-N5fA.png" /><figcaption>merge method explained. <a href="https://www.tutorialspoint.com/python_pandas/python_pandas_merging_joining.htm">Source</a>.²</figcaption></figure><p>Now let’s merge the rdf and price_df DataFrame objects.</p><pre>rdf = pd.merge(<br>    rdf,<br>    price_df,<br>    left_on = &#39;origin&#39;,<br>    right_on = &#39;country&#39;,<br>    how = &#39;left&#39;<br>)<br>rdf.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*dR8Vrn0zJGOauE9vFMydvw.png" /><figcaption>rdf &amp; price_df merged</figcaption></figure><p><strong><em>loc</em></strong></p><p>Creating a new column price and setting the column value based on conditions using loc. This method is surely faster than for loop or apply.</p><pre>abc_df.loc[abc_df[&#39;origin&#39;]==&#39;usa&#39;,&#39;price&#39;] = 50000<br>abc_df.loc[abc_df[&#39;origin&#39;]==&#39;europe&#39;,&#39;price&#39;] = 45000<br>abc_df.loc[abc_df[&#39;origin&#39;]==&#39;japan&#39;,&#39;price&#39;] = 85000</pre><p><strong><em>mapping</em></strong></p><p>Using the <strong><em>map() </em></strong>function to map values based on the dictionary’s key and assigns the corresponding value.</p><pre>p_dict = {&#39;usa&#39;:50000,&#39;europe&#39;:45000,&#39;japan&#39;:85000}<br>mpg_df[&#39;price&#39;]=mpg_df[&#39;origin&#39;].map(p_dict)<br>mpg_df.head()</pre><p>Before we declare that we’ve mastered all the essential functions in Pandas for Data Wrangling. There is one important concept that is still pending :</p><h4><strong>Groupby</strong></h4><p><strong><em>groupby()</em></strong> function is used to divide the data into groups. It helps aggregate data in a way that is easy to interpret and compute operations on.</p><p>Let’s say I want to find the average of all values based on ‘origin’.</p><pre>mpg_df.groupby(&#39;origin&#39;).mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*cM_YbTcuNfJadb0FEV4Rjw.png" /><figcaption>average of all values grouped by origin</figcaption></figure><pre>&#39;&#39;&#39;Grouping based on multiple columns &amp; calculate sum of cylinders used in each origin, will return a series&#39;&#39;&#39;</pre><pre>mpg_df.groupby([&#39;origin&#39;,&#39;price&#39;])[&#39;cylinders&#39;].sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*MGMV_xr3lUgY8Cmf1GMY0g.png" /><figcaption>sum of cylinders grouped by origin &amp; price</figcaption></figure><p>As we already know, to get the result in the form of a DF instead of series we use double square brackets.</p><pre>mpg_df.groupby([&#39;origin&#39;,&#39;price&#39;])[[&#39;cylinders&#39;]].sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*GDfl9o3h9ZKtEHAMx0D1aw.png" /><figcaption>groupby DF</figcaption></figure><pre>mpg_df.groupby([&#39;origin&#39;,&#39;name&#39;])[&#39;name&#39;].count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*Vy-1x2JhDAK9Pg0iweYA8w.png" /><figcaption>name grouped by origin</figcaption></figure><p><strong><em>Groupby </em></strong>can be used effectively in different contexts to obtain different results. Based on the application, different arguments and functions can be used in combination with it.</p><p>Groupby can be a topic for an article in itself. So for a more detailed understanding of groupby, you can go through the following Medium articles that I found to be interesting &amp; covering all the bases:</p><ul><li><a href="https://towardsdatascience.com/pandas-groupby-explained-453692519d0">Pandas Groupby explained</a> and <a href="https://towardsdatascience.com/11-examples-to-master-pandas-groupby-function-86e0de574f38">11 Examples of Groupby</a> by <a href="https://medium.com/u/2cf6b549448">Soner Yıldırım</a></li><li><a href="https://towardsdatascience.com/efficient-data-summarizing-and-analysis-using-pandas-groupby-function-7b2cc9eff186">Efficient Data Summarizing &amp; Analysis</a> by <a href="https://medium.com/u/8a36b941a136">Rashida Nasrin Sucky</a></li><li><a href="https://towardsdatascience.com/ultimate-pandas-guide-mastering-the-groupby-104306251739">Guide to mastering groupby</a> by <a href="https://medium.com/u/da6d67cb69f3">Skyler Dale</a></li></ul><p><em>Yes! You have now learned the art of Data Wrangling with Pandas. Most of the commands &amp; functions in Pandas are straightforward and easy to implement as long as we have clarity on what we want to achieve with the data at hand.</em></p><p><strong><em>Summary</em></strong></p><p>Concepts we’ve covered in this article:</p><ul><li><strong><em>Loading </em></strong>Data into a DataFrame</li><li><strong><em>Exploring </em></strong>the Data</li><li><strong><em>Manipulating </em></strong>the Data using different methods</li></ul><p><em>Practicing on a few datasets and doing some StackOverflow searches is all a part of the process.</em></p><blockquote>The Deeper You Dig, The More You Find</blockquote><p><strong><em>Wrapping up</em></strong></p><p>Thanks to anyone who’s made it this far, I hope you found this article helpful. Please share your feedback/queries in the comments. Now, it&#39;s time for you to put your Data Wrangling skills to use. Wish you luck!</p><p><em>If you found this article interesting and are passionate about Data Science/Machine Learning, hit </em><a href="https://medium.com/@mahadeveaswar"><em>follow</em></a><em> and feel free to add me on </em><a href="https://www.linkedin.com/in/mahadev-easwar/"><em>LinkedIn</em></a><em>.</em></p><pre>References:<br>1.<a href="https://pypistats.org/">https://pypistats.org/</a><br>2.<a href="https://www.tutorialspoint.com/python_pandas/python_pandas_merging_joining.htm">https://www.tutorialspoint.com/python_pandas/python_pandas_merging_joining.htm</a><br>3.<a href="https://pandas.pydata.org/docs/reference/frame.html">https://pandas.pydata.org/docs/reference/frame.html</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a5cb698287" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/essential-data-wrangling-skills-for-data-scientists-in-2021-87a5cb698287">Essential Data Wrangling Skills for Data Scientists in 2021</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Data Structures in Python]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-data-structures-in-python-a235d5c5b3a4?source=rss-354de2ec0117------2</link>
            <guid isPermaLink="false">https://medium.com/p/a235d5c5b3a4</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Mahadev Easwar]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 15:53:48 GMT</pubDate>
            <atom:updated>2020-12-18T16:09:21.633Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Key concepts in Python Programming</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5W1qoRNMOfwd7jx_" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Python is one of the most popular programming languages with a wide range of applications. Its straight-forward and easy-to-use syntax has made it a preferred programming language for both beginners and experts. Python is said to be one of the most visited tags on Stack Overflow and one of the fastest-growing ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*frv-jgEeQWmzjnSjr2nm2A.png" /><figcaption>Popularity Trend of Python vs Other Languages. <a href="https://pypl.github.io/PYPL.html">Source</a> .</figcaption></figure><p>Before learning the core components and packages of your area of application, understanding the following Data Structures in Python is imperative:</p><ul><li>List</li><li>Set</li><li>Dictionary</li><li>Tuple</li></ul><p><strong>What is a Data Structure?</strong></p><p>A data structure is a format for storing, organizing, and processing data. They are the fundamental constructs around which powerful algorithms are built.</p><p><strong><em>List in Python</em></strong></p><blockquote>A list is a data structure that contains multiple items, comma separated and enclosed within square brackets. The items within a list can be of varying data type, including another list. It can be modified after creation(mutable). The elements in a list are indexed, with 0 being the first index.</blockquote><p>I hear you. Enough theory, let’s code.</p><pre># Creating a list with varying elements including another list<br>dlist = [10,&#39;element&#39;,[100,200,&#39;inlist&#39;]]<br>print(dlist)<br>&gt;&gt;&gt; [10, &#39;element&#39;, [100, 200, &#39;inlist&#39;]]</pre><pre># Accessing elements in a list<br>dlist[1]<br>&gt;&gt;&gt; &#39;element&#39;</pre><pre>dlist[0:2]<br>&gt;&gt;&gt; [10, &#39;element&#39;]</pre><pre>dlist[-1]<br>&gt;&gt;&gt; [100, 200, &#39;inlist&#39;]</pre><pre># Accessing elements inside the embedded list<br>dlist[-1][2]<br>&gt;&gt;&gt; &#39;inlist&#39;</pre><pre># Iterating over a string<br>list(&#39;element&#39;)<br>&gt;&gt;&gt; [&#39;e&#39;, &#39;l&#39;, &#39;e&#39;, &#39;m&#39;, &#39;e&#39;, &#39;n&#39;, &#39;t&#39;]</pre><p>Like I mentioned before, index starts with 0 in Python. But you must be wondering when I mention [0:2], why the 3rd element in the list did not get printed. This is because when accessing lists like [0,range], only the elements till the index of (range-1) are returned. Elements inside an embedded list can be accessed using multiple square brackets as shown above.</p><p>Lists provide the following functionalities :</p><ol><li>append</li><li>insert</li><li>pop</li><li>remove</li><li>sort</li><li>extend</li></ol><pre># Adding a new element to the list<br>dlist.append(&#39;new_append&#39;)<br>&gt;&gt;&gt; [10, &#39;element&#39;, [100, 200, &#39;inlist&#39;], &#39;new_append&#39;]</pre><pre># Inserting a new element using index<br>dlist.insert(1,&#39;position_one&#39;)<br>&gt;&gt;&gt; [10, &#39;position_one&#39;, &#39;element&#39;, [100, 200, &#39;inlist&#39;], &#39;new_append&#39;]</pre><pre># Removing value from the list<br>dlist.remove(&#39;element&#39;)<br>&gt;&gt;&gt; [10, &#39;position_one&#39;, [100, 200, &#39;inlist&#39;], &#39;new_append&#39;]</pre><pre># Pop out the last element in the list<br>dlist.pop()<br>&gt;&gt;&gt; &#39;new_append&#39;<br>print(dlist)<br>&gt;&gt;&gt; [10, &#39;position_one&#39;, [100, 200, &#39;inlist&#39;]]</pre><pre># Pop element using index<br>dlist.pop(1)<br>&gt;&gt;&gt; &#39;position_one&#39;<br>print(dlist)<br>&gt;&gt;&gt; [10, [100, 200, &#39;inlist&#39;]]</pre><pre># New list created &amp; sorted with inbuilt function<br>nlist = [50,20,70,40]<br>nlist.sort()<br>print(nlist)<br>&gt;&gt;&gt; [20, 40, 50, 70]<br>nlist.sort(reverse=True)<br>print(nlist)<br>&gt;&gt;&gt; [70, 50, 40, 20]</pre><pre># Extending a list with elements from another list<br>dlist.extend(nlist)<br>print(dlist)<br>&gt;&gt;&gt; [10, [100, 200, &#39;inlist&#39;], 70, 50, 40, 20]</pre><pre># Lists can also be concatenated<br>clist = nlist + dlist<br>print(clist)<br>&gt;&gt;&gt; [70, 50, 40, 20, 10, [100, 200, &#39;inlist&#39;]]</pre><ul><li>By default the sort function for lists has the parameter (reverse=False), meaning, the list will be returned in ascending order if the sort function is called</li><li>If (reverse=True), the list will be returned in descending order</li><li>The extend function takes all elements from the list passed as argument and appends them to the calling list</li><li>The append function will not work the same way. Passing a list as argument to the function will append it as a list element to the calling list as shown below</li></ul><pre>dlist.append(nlist)<br>print(dlist)<br>&gt;&gt;&gt; [10, [100, 200, &#39;inlist&#39;], 70, 50, 40, 20, [70, 50, 40, 20]]</pre><ul><li>List Comprehensions plays an interesting role in helping code in a clear &amp; concise way</li><li>List Comprehensions are more efficient than for loops</li></ul><p>Checkout the example below to understand how.</p><pre># Using for loops with list<br>a = [1,2,3,4,5]<br>b = []<br>for i in a:<br>    if i%2!=0:<br>        b.append(i*2)<br>    else:<br>        b.append(i)<br>print(b)<br>&gt;&gt;&gt; [2, 2, 6, 4, 10]</pre><pre># Using list comprehension<br>a = [1,2,3,4,5]<br>b = [var*2 if var%2!=0 else var for var in a ]<br>print(b)<br>&gt;&gt;&gt; [2, 2, 6, 4, 10]</pre><p><strong><em>Set in Python</em></strong></p><blockquote>Sets are unordered and cannot contain duplicate values. Set items cannot be accessed using index. Items in a set are enclosed within curly braces {}.</blockquote><pre># Creating a set<br>var = {&#39;alphabet&#39;,&#39;item&#39;,&#39;element&#39;}<br>print(var)<br>&gt;&gt;&gt; {&#39;alphabet&#39;, &#39;element&#39;, &#39;item&#39;}</pre><pre># Iterating over a string<br>set(&#39;element&#39;)<br>&gt;&gt;&gt; {&#39;e&#39;, &#39;l&#39;, &#39;m&#39;, &#39;n&#39;, &#39;t&#39;}</pre><pre>vel = {&#39;item&#39;,&#39;term&#39;,&#39;ball&#39;}</pre><pre># Intersection of sets<br>vel.intersection(var)<br>&gt;&gt;&gt; {&#39;item&#39;}</pre><pre># Difference of sets<br>var.difference(vel)<br>&gt;&gt;&gt; {&#39;alphabet&#39;, &#39;element&#39;}</pre><pre># Union of sets<br>var.union(vel)<br>&gt;&gt;&gt; {&#39;alphabet&#39;, &#39;term&#39;, &#39;item&#39;, &#39;ball&#39;, &#39;element&#39;}</pre><pre># Removing element from a set<br>var.remove(&#39;item&#39;)<br>var<br>&gt;&gt;&gt; {&#39;alphabet&#39;, &#39;element&#39;}</pre><ul><li>Intersection of sets return the elements which are present in both the sets</li><li>Difference of sets return the elements which are present in the calling set, but not present in the set passed as an argument</li><li>Union of sets returns all the distinct elements put together</li><li>Set function can also come in handy when we need the distinct elements from a list</li><li>The ‘issubset’ function helps checks if all elements of the calling set are present in the set passed as argument</li></ul><pre># selecting distinct elements from a list<br>lst = [&#39;a&#39;,&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;d&#39;]<br>set(lst)<br>&gt;&gt;&gt; {&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;}</pre><pre># subset check<br>a = {1,2,3,4,5}<br>b = {2,3}<br>b.issubset(a)<br>&gt;&gt;&gt; True</pre><p><strong><em>Dictionary in Python</em></strong></p><blockquote>Dictionaries are collections which are unordered, enclosed within curly braces {} and stored as key-value pairs.</blockquote><ul><li>Elements in a dictionary can be accessed using a key instead of index</li><li>If we have a dictionary using same key for multiple values, the value stored will be the one mapped with the last key</li></ul><pre># Creating a dictionary<br>d = {&#39;country&#39;:&#39;India&#39;,&#39;currency&#39;:&#39;rupees&#39;,&#39;capital&#39;:&#39;Delhi&#39;}</pre><pre># Accessing element from dictionary<br>d[&#39;currency&#39;]<br>&gt;&gt;&gt; &#39;rupees&#39;</pre><pre># Same key with multiple values<br>d = {&#39;country&#39;:&#39;India&#39;,&#39;capital&#39;:&#39;Delhi&#39;,&#39;currency&#39;:&#39;dollar&#39;, &#39;currency&#39;:&#39;rupees&#39;}<br>d<br>&gt;&gt;&gt; {&#39;country&#39;: &#39;India&#39;, &#39;capital&#39;: &#39;Delhi&#39;, &#39;currency&#39;: &#39;rupees&#39;}</pre><pre># Modifying values in a dictionary<br>d[&#39;capital&#39;] = &#39;New Delhi&#39;<br>d<br>&gt;&gt;&gt; {&#39;country&#39;: &#39;India&#39;, &#39;capital&#39;: &#39;New Delhi&#39;, &#39;currency&#39;: &#39;rupees&#39;}</pre><pre># Adding new element to the dictionary<br>d[&#39;culture&#39;] = &#39;Diverse&#39;<br>d<br>&gt;&gt;&gt; {&#39;country&#39;: &#39;India&#39;,&#39;capital&#39;: &#39;New Delhi&#39;,&#39;currency&#39;: &#39;rupees&#39;,<br> &#39;culture&#39;: &#39;Diverse&#39;}</pre><ul><li>Dictionaries are very useful when it comes to accessing elements quickly, they use hashing</li><li>It does not iterate over all the items to find the value like lists. Instead uses the key to directly access the item value</li></ul><pre>ldict = {&#39;country&#39;:&#39;India&#39;,&#39;capital&#39;:&#39;Delhi&#39;,<br>&#39;MCs&#39;:[&#39;Chennai&#39;,&#39;Delhi&#39;,&#39;Kolkata&#39;,&#39;Mumbai&#39;]}</pre><pre># Accessing keys, values of a dictionary<br>ldict.keys()<br>&gt;&gt;&gt; dict_keys([&#39;country&#39;, &#39;capital&#39;, &#39;MCs&#39;])</pre><pre>ldict.values()<br>&gt;&gt;&gt; dict_values([&#39;India&#39;, &#39;Delhi&#39;, [&#39;Chennai&#39;, &#39;Delhi&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;]])</pre><pre># Accessing respective key-value of each element<br>ldict.items()<br>&gt;&gt;&gt; dict_items([(&#39;country&#39;, &#39;India&#39;), (&#39;capital&#39;, &#39;Delhi&#39;), (&#39;MCs&#39;, [&#39;Chennai&#39;, &#39;Delhi&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;])])</pre><pre># Accessing value using get function<br>ldict.get(&#39;country&#39;)<br>&gt;&gt;&gt; &#39;India&#39;</pre><pre># Accessing one of the above in the form of a list<br>list(ldict.keys())<br>&gt;&gt;&gt; [&#39;country&#39;, &#39;capital&#39;, &#39;MCs&#39;]</pre><ul><li>Dictionaries are quick, easy to use, and flexible</li><li>A dictionary can be extended to accommodate the key-value pairs from another dictionary using the update function</li></ul><pre># Updating a dictionary<br>nd = {&#39;first&#39;:&#39;one&#39;,&#39;second&#39;:&#39;two&#39;}<br>ldict.update(nd)<br>ldict<br>&gt;&gt;&gt; {&#39;country&#39;: &#39;India&#39;,<br> &#39;capital&#39;: &#39;Delhi&#39;,<br> &#39;MCs&#39;: [&#39;Chennai&#39;, &#39;Delhi&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;],<br> &#39;first&#39;: &#39;one&#39;,<br> &#39;second&#39;: &#39;two&#39;}</pre><pre># Removing an element from the dictionary<br>del ldict[&#39;second&#39;]<br>ldict<br>&gt;&gt;&gt; {&#39;country&#39;: &#39;India&#39;,&#39;capital&#39;: &#39;Delhi&#39;,&#39;MCs&#39;: [&#39;Chennai&#39;, &#39;Delhi&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;],&#39;first&#39;: &#39;one&#39;}</pre><p><strong><em>Tuple in Python</em></strong></p><blockquote>Tuples are another data structure similar to lists, but they are immutable. They are ordered and values can be accessed using index. The values are comma-separated and enclosed within parenthesis.</blockquote><ul><li>No element can be added, removed or modified once a tuple is created</li><li>Tuple can have duplicate values since they are indexed</li></ul><pre># Creating a tuple<br>tup = (1,2,4,2,5)<br>tup<br>&gt;&gt;&gt; (1, 3, 4, 3, 5)</pre><pre># Count of occurrence of value<br>tup.count(3)<br>&gt;&gt;&gt; 2</pre><pre># Index of a value<br>tup.index(5)<br>&gt;&gt;&gt; 4</pre><pre># Max and min values from a tuple<br>min(tup)<br>&gt;&gt;&gt; 1<br>max(tup)<br>&gt;&gt;&gt; 5</pre><pre># Concatenating tuples<br>tt = (5, 6, 7, [10, 30])<br>tup+tt<br>&gt;&gt;&gt; (1, 3, 4, 3, 5, 5, 6, 7, [10, 30])</pre><pre># Membership<br>6 in tt<br>&gt;&gt;&gt; True</pre><p>Although a tuple is immutable, if a mutable object is present in the tuple, value of that object can be modified. Similar to lists, slicing operations are allowed on tuples using the index of the values.</p><pre># List within a tuple<br>tt = (5,6,7,[10,20])<br>tt<br>&gt;&gt;&gt; (5,6,7,[10,20])</pre><pre># Slicing values in a tuple<br>tt[1:3]<br>(6, 7)</pre><pre># Modifying the value inside the list<br>tt[3][1] = 30<br>tt<br>&gt;&gt;&gt; (5, 6, 7, [10, 30])</pre><ul><li>Tuple iteration is faster than iterating through a list</li><li>Tuple packing and unpacking are the most useful operations when it comes to passing multiple arguments to a function or getting multiple values in the response and assigning to respective attributes/fields</li></ul><pre># Unpacking the values from a tuple<br>x,*y,z = (1,2,3,4,5,6,7,8)<br>x<br>&gt;&gt;&gt; 1<br>y<br>&gt;&gt;&gt; [2, 3, 4, 5, 6, 7]<br>z<br>&gt;&gt;&gt; 8</pre><pre># Packing &amp; Unpacking<br>t = (’data’, &#39;analysis’, &#39;munging’, &#39;science’)<br>w,x,y,z = t<br>w,x,y,z<br>&gt;&gt;&gt; (’data’, &#39;analysis’, &#39;munging’, &#39;science’)</pre><p><strong><em>Summary</em></strong></p><p>Concepts we’ve covered in this article:</p><ul><li>What Data Structure means</li><li>Inbuilt data structures in Python</li><li>Functionalities offered by the data structures</li></ul><p>While this is just an overview of how effective Data Structures are, I have learnt that understanding these concepts is crucial for Programming in Python. To learn more, refer the Python data structures <a href="https://docs.python.org/3/tutorial/datastructures.html">documentation</a>.</p><p><strong><em>Wrapping up</em></strong></p><p>Thanks to anyone who’s made it this far, I hope you found this article helpful. Please share your feedback/queries in the comments. Now, its time for you to begin your journey in Python. Start playing around with what you’ve learned today. Wish you luck!</p><p><em>This is my first article and I wanted to cover the key concepts in Python Programming before moving on to Data Science. If you found this article interesting and are passionate about Data Science/Machine Learning, hit </em><a href="https://medium.com/@mahadeveaswar"><em>follow</em></a><em> and feel free to add me on </em><a href="https://www.linkedin.com/in/mahadev-easwar/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a235d5c5b3a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-data-structures-in-python-a235d5c5b3a4">Introduction to Data Structures in Python</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>
    </channel>
</rss>