<?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 Priyanshu Madan on Medium]]></title>
        <description><![CDATA[Stories by Priyanshu Madan on Medium]]></description>
        <link>https://medium.com/@pmadan.illinois?source=rss-32a4b20b6ca7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OaUKZoNr71J5LBzqOqRhuA.png</url>
            <title>Stories by Priyanshu Madan on Medium</title>
            <link>https://medium.com/@pmadan.illinois?source=rss-32a4b20b6ca7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:43:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pmadan.illinois/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[Extract data from Crunchbase API using Python]]></title>
            <link>https://medium.com/priyanshumadan/extract-data-from-crunchbase-api-using-python-8e99ed6bc73e?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e99ed6bc73e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[crunchbase]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[job-hunting]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 23:21:49 GMT</pubDate>
            <atom:updated>2020-06-11T20:47:17.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extract data from Crunchbase API V4.0 using Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q_ZBRC10ZbKWnDzv" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Given the current pandemic situation, there aren’t a lot of companies actively hiring. Alongside applying to career sites, I wanted to have a data-driven approach to my problem. Later in this series, I’ll use NLP and a Jobs API to find jobs that best match my profile. But for now, this post focusses on identifying high growth companies from CrunchBase, which I can then target for jobs.</p><p>Recently, Crunchbase released its API v4.0 and there isn’t any comprehensive documentation available online to take advantage of this powerful platform using python. So I thought to take a stab at it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UsGeSiYkZe___SJFZEqt9g.png" /></figure><h4>What is Crunchbase?</h4><p>If you are reading this post I am going to assume that you already know what CrunchBase is. But if you don&#39;t, in simple terms it is a platform that helps users get all the information about companies all over the world. It includes information such as Revenue, Investors, Number of employees, contact information, and more. You can visit <a href="https://data.crunchbase.com/docs/getting-started">Cruncbase Data</a> to get a complete list of data points.</p><p>CrunchBase API allows the developers to leverage this same data that powers <a href="http://www.crunchbase.com/">CrunchBase.com</a> and allow them to make their own application or website.</p><p>For my use-case, I am going to extract information for all the companies in Los Angeles</p><p><strong>Let&#39;s get started</strong></p><p><strong>Step 1: Get CrunchBase API key and request URL</strong></p><p>Again I am going to assume you have the API key handy, but if you don&#39;t, you can visit <a href="https://data.crunchbase.com/docs/using-the-api">Crunchbase Data</a> and register to get access to the API.</p><p>Next, we need the request URL. You can visit <a href="https://data.crunchbase.com/docs/using-swaggerhub">SwaggerHub</a> on Crunchbase Data to get a complete list of Crunchbase endpoints along with their own examples that you can try yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czJSaJmvEvxQ9IS6_J4L4w.png" /><figcaption>SwaggerHub</figcaption></figure><p>The API URL will be of the following format:</p><p>https://api.crunchbase.com/api/v4/entities/organizations/crunchbase?user_key=INSERT_YOUR_API_KEY_HERE</p><p>Since I am searching for organizations in LA, I will be using “POST /search/organizations” URL.</p><p>Now let&#39;s get to the actual coding part</p><p><strong>Step 2: Request data using python</strong></p><p><strong>Import all necessary Packages</strong></p><pre>import requests<br>import json<br>import pandas as pd<br>from pandas.io.json import json_normalize </pre><p>We will use the request module to send an API request to Crunchbase.</p><p><strong>Define your API user key</strong></p><pre>userkey = {&quot;user_key&quot;:&quot;INSERT_YOUR_API_KEY_HERE&quot;}</pre><p><strong>Define search query parameter</strong></p><p>The search query parameter is the query that you will pass to the request API to get the required data. (You can see example queries on SwaggerHub)</p><p>Since I am finding companies in LA, my query will look something like this:</p><pre>query = {<br>&quot;field_ids&quot;: [<br>&quot;identifier&quot;,<br>&quot;location_identifiers&quot;,<br>&quot;short_description&quot;,<br>&quot;categories&quot;,<br>&quot;num_employees_enum&quot;,<br>&quot;revenue_range&quot;,<br>&quot;operating_status&quot;,<br>&quot;website&quot;,<br>&quot;linkedin&quot;<br>],</pre><pre>&quot;limit&quot;: 1000,<br>&quot;query&quot;: [<br>{<br>&quot;type&quot;: &quot;predicate&quot;,<br>&quot;field_id&quot;: &quot;location_identifiers&quot;,<br>&quot;operator_id&quot;: &quot;includes&quot;,<br>&quot;values&quot;: [<br>&quot;4ce61f42-f6c4-e7ec-798d-44813b58856b&quot; #UUID FOR LOS ANGELES<br>]<br>},<br>{<br>&quot;type&quot;: &quot;predicate&quot;,<br>&quot;field_id&quot;: &quot;facet_ids&quot;,<br>&quot;operator_id&quot;: &quot;includes&quot;,<br>&quot;values&quot;: [<br>&quot;company&quot;<br>]<br>}<br>]<br>}</pre><p>The first part of the query is <strong>“field_ids”</strong>. Here I mention all the entities that I need from CrunchBase. which in this case is [identifier, location_identifier, short_description, categories, num_employees_enum, revenue_range, operating_status, website, LinkedIn].</p><p>You can get a complete list of field_ids from SwaggerHub by clicking on the required API example and then switching to “schema” under description as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4N5FhSdj0cexUlDj6x2WIQ.gif" /><figcaption>How to get the complete list of field_ids</figcaption></figure><p><strong>“limit”: 1000</strong> defines the number of results the query returns. In this case, it is 1000 which is the maximum limit for Crunchbase Pro.</p><p>“query”: {} defines the actual query part. In this case, I want to find companies in Los Angeles. So I have defined the “location_identifier” value as</p><p>“4ce61f42-f6c4-e7ec-798d-44813b58856b”</p><p>The above string is the UUID (universally unique identifier) of Los Angeles.</p><p><strong>To get UUID of anything:</strong></p><p><em>Go to SwaggerHub -&gt; GET /autocomplete -&gt; Click “Try it out” -&gt; type in query in the querybox -&gt; Execute -&gt; copy the UUID in response body.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WTQcmabPJ5TPv4rwrzvzeg.gif" /><figcaption>Get UUID for anything</figcaption></figure><p>The second part of the query is what we want Crunchbase to return, which in this case the company data. Hence we have set “facet_id” value as “company”.</p><p>Now that we have our query setup, we will now create 2 functions that will return the number of companies and extract data and save it as a pandas data frame. Here, POST request with API URL, userkey as a parameter, and passing query as json.</p><pre><strong>def company_count(query):</strong></pre><pre>    r = requests.post(&quot;https://api.crunchbase.com/api/v4/searches/organizations&quot;, params = userkey , json = query)<br>    result = json.loads(r.text)<br>    total_companies = result[&quot;count&quot;]<br>    return total_companies</pre><pre><strong>def url_extraction(query):</strong></pre><pre>    global raw</pre><pre>    r = requests.post(&quot;https://api.crunchbase.com/api/v4/searches/organizations&quot;, params = userkey , json = query)<br>    result = json.loads(r.text)<br>    normalized_raw = json_normalize(result[&#39;entities&#39;])<br>    raw = raw.append(normalized_raw,ignore_index=True)</pre><p>Now since there are more than 1000 companies, I had to loop my query till I get all my results. The way I did this was by adding “after_id” key in the query part and the last UUID as the key. By doing this the loop will fetch new data after the last UUID that was fetched.</p><pre>raw=pd.DataFrame()</pre><pre>comp_count = company_count(query)</pre><pre>data_acq = 0</pre><pre># data_acq</pre><pre>while data_acq &lt; comp_count:<br>    if data_acq != 0:<br>        last_uuid = raw.uuid[len(raw.uuid)-1]<br>        query[&quot;after_id&quot;] = last_uuid<br>        url_extraction(query)<br>        data_acq = len(raw.uuid)<br>    else:<br>        if &quot;after_id&quot; in query:<br>        query = query.pop(&quot;after_id&quot;)<br>        url_extraction(query)<br>        data_acq = len(raw.uuid)<br>        else:<br>            url_extraction(query)<br>            data_acq = len(raw.uuid)</pre><p>This is how the <strong>“raw”</strong> data frame looks after extraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WECwZ5ximrH8mkwGzeOciA.png" /><figcaption>Raw data frame screenshot</figcaption></figure><p><strong>Cleaning the data</strong></p><p>Now its time to clean the data frame.</p><p>I made 2 dictionaries to replace values in revenue and employee number column so that it is more readable. And Changed the column names and saved it as master table.</p><pre>revenue_range = {<br>&quot;r_00000000&quot;: &quot;Less than $1M&quot;,<br>&quot;r_00001000&quot;: &quot;$1M to $10M&quot;,<br>&quot;r_00010000&quot;: &quot;$10M to $50M&quot;,<br>&quot;r_00050000&quot;: &quot;$50M to $100M&quot;,<br>&quot;r_00100000&quot;: &quot;$100M to $500M&quot;,<br>&quot;r_00500000&quot;: &quot;$500M to $1B&quot;,<br>&quot;r_01000000&quot;: &quot;$1B to $10B&quot;,<br>&quot;r_10000000&quot;: &quot;$10B+&quot;}</pre><pre>employee_range = {<br>&quot;c_00001_00010&quot;: &quot;1-10&quot;,<br>&quot;c_00011_00050&quot;: &quot;11-50&quot;,<br>&quot;c_00051_00100&quot;: &quot;51-100&quot;,<br>&quot;c_00101_00250&quot;: &quot;101-250&quot;,<br>&quot;c_00251_00500&quot;: &quot;251-500&quot;,<br>&quot;c_00501_01000&quot;: &quot;501-1000&quot;,<br>&quot;c_01001_05000&quot;: &quot;1001-5000&quot;,<br>&quot;c_05001_10000&quot;: &quot;5001-10000&quot;,<br>&quot;c_10001_max&quot;: &quot;10001+&quot;}</pre><pre>master = pd.DataFrame()</pre><pre>master[&quot;uuid&quot;] = raw[&quot;uuid&quot;]</pre><pre>master[&quot;company&quot;] = raw[&quot;properties.identifier.value&quot;]</pre><pre>master[&quot;description&quot;] = raw[&quot;properties.short_description&quot;]</pre><pre>master[&quot;categories&quot;] = raw[&quot;properties.categories&quot;].apply(lambda x: list(map(itemgetter(&#39;value&#39;), x)if isinstance(x, list) else [&quot;Not found&quot;])).apply(lambda x : &quot;,&quot;.join(map(str, x)))</pre><pre>master[&quot;location&quot;] = raw[&quot;properties.location_identifiers&quot;].apply(lambda x: list(map(itemgetter(&#39;value&#39;), x)if isinstance(x, list) else [&quot;Not found&quot;])).apply(lambda x : &quot;,&quot;.join(map(str, x)))</pre><pre>master[&quot;revenue&quot;] = raw[&quot;properties.revenue_range&quot;].map(revenue_range)</pre><pre>master[&quot;num_of_employees&quot;] = raw[&quot;properties.num_employees_enum&quot;].map(employee_range)</pre><pre># master[&quot;rank&quot;] = raw[&quot;properties.rank_org_company&quot;]</pre><pre>master[&quot;linkedin&quot;] = raw[&quot;properties.linkedin.value&quot;]</pre><pre>master[&quot;website&quot;] = raw[&quot;properties.website.value&quot;]</pre><pre>master[&quot;status&quot;] = raw[&quot;properties.operating_status&quot;]</pre><pre>master=master.fillna(&quot;NA&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1T_oJUdM0zuYZzgh1D8FpQ.png" /><figcaption>cleaning step code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqNOcmfa25USAGmpOxmtVA.png" /></figure><p>And Viola We have successfully extracted company data from CrunchBase API using python!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e99ed6bc73e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/extract-data-from-crunchbase-api-using-python-8e99ed6bc73e">Extract data from Crunchbase API using Python</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting multiple columns of a dataset and storing it as a data frame using Pandas]]></title>
            <link>https://medium.com/priyanshumadan/extracting-multiple-columns-of-a-dataset-and-storing-it-as-a-data-frame-python-pandas-7e005dbfc8ff?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e005dbfc8ff</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 01:19:04 GMT</pubDate>
            <atom:updated>2019-06-11T05:21:43.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*matF0dsuWR5iP19V" /><figcaption>Photo by <a href="https://unsplash.com/@millerthachiller?utm_source=medium&amp;utm_medium=referral">Pascal Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today I learned how to extract multiple columns from a dataset and store it in a data frame for further analysis.</p><p>In this section, I want to display the following columns of the volcano dataset that caused a Tsunami (‘Year’, ‘Month’, ‘day’, ‘Name’,’Location’,’Country’).</p><pre>import pandas as pd<br>vol = pd.read_csv(&quot;vol.txt&quot;,sep=&quot;\t&quot;,header=0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*ljJRWLTgV7n8df5I.png" /></figure><p>There are 2 parts:</p><p><strong>1) Extraction of data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*xkE7E4RL6vshIr65.png" /></figure><p><strong>tsunami_vol </strong>data frame was created with required columns using <strong>Dataframe()</strong> function of pandas and set <strong>column = [“column names”]</strong></p><p><strong>2) Using subset to extract required rows of data (volcanos that caused tsunami)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*9LJrwLJ13DZkKTpx.png" /><figcaption>Top 10 volcanos that caused a tsunami</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e005dbfc8ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/extracting-multiple-columns-of-a-dataset-and-storing-it-as-a-data-frame-python-pandas-7e005dbfc8ff">Extracting multiple columns of a dataset and storing it as a data frame using Pandas</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rearrange the order of bars in Barplot [R]]]></title>
            <link>https://medium.com/priyanshumadan/rearrange-the-order-of-bars-in-barplot-r-3e6ce961fa81?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e6ce961fa81</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 01:07:21 GMT</pubDate>
            <atom:updated>2019-06-11T01:07:21.930Z</atom:updated>
            <content:encoded><![CDATA[<p>While I was doing my <a href="https://medium.com/priyanshumadan/california-housing-analysis-r-70ccf7852123"><em>California Housing Analysis</em></a>, I faced a problem where the bars of the bar plots were not in the order they were supposed to be in.</p><pre>barplot( height = rowsum(household_income_inland$households,household_income_inland$incomecut)[,1]<br>         , las = 1<br>         , col = &quot;#A3A500&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (INLAND)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qfjpprj-xAFGI7lH.png" /></figure><p>You can see from the plot above that the bars are not in chronological order (10k-20k,20k-30k). The reason this happens because R arranges the labels in ascending order. (special characters &lt; 0 &lt; 1 &lt; 2…..)</p><p>The way I solved this problem was by creating a character vector <strong>“headers_income”</strong> of the bar labels in order.</p><pre>headers_income &lt;- c(&quot;0-10k&quot;, &quot;10k-20k&quot;, &quot;20k-30k&quot;,&quot;30k-40k&quot;, &quot;40k-50k&quot;, &quot;50k-60k&quot;,&quot;60k-70k&quot;,&quot;70k-80k&quot;,&quot;80k-90k&quot;,&quot;90k-100k&quot; <br>                    ,&quot;100k-110k&quot;,&quot;110k-120k&quot;,&quot;120k-130k&quot;,&quot;130k-140k&quot;,&quot;140k-150k&quot;,&quot; &gt;150k&quot;)</pre><p>Then I wrote <strong>“<em>[headers_income]</em>”</strong> at the end of the <strong><em>rowsum()</em></strong> function.</p><pre>barplot( height = rowsum(household_income_inland$households,household_income_inland$incomecut)[,1][headers_income]<br>         , las = 1<br>         , col = &quot;#A3A500&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (INLAND)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><p><strong>Done!</strong></p><p><strong>The Bars are now in order</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5esysk2-NiCl2E-A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e6ce961fa81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/rearrange-the-order-of-bars-in-barplot-r-3e6ce961fa81">Rearrange the order of bars in Barplot [R]</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[California Housing Analysis [R]]]></title>
            <link>https://medium.com/priyanshumadan/california-housing-analysis-r-70ccf7852123?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/70ccf7852123</guid>
            <category><![CDATA[california]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 00:56:05 GMT</pubDate>
            <atom:updated>2019-06-11T00:56:05.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4Vla6WhNpe1y-8WlOvuhQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jesseroberts?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jesse Roberts</a> on <a href="https://unsplash.com/search/photos/house?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Background</h3><p>I recently visited my brother in California and fell in love with it! The beautiful landscape and the energetic vibe really caught my attention. And obviously, you find some of the best companies in the world here in Silicon Valley! It just got me wondering- how much would it take to own a house here?</p><h3>Data</h3><p>I started exploring a couple of housing datasets. Zillow keeps an impressive amount of data, but I found it to be a bit of overkill for the purpose of this analysis. I found this introductory dataset on Kaggle derived from the California census apt for my exploratory analysis</p><blockquote><em>The data pertains to the houses found in a given California district and some summary stats about them based on the 1990 census data</em></blockquote><p>The dataset has the following columns:</p><ol><li><strong>longitude:</strong> A measure of how far west a house is; a higher value is farther west</li><li><strong>latitude:</strong> A measure of how far north a house is; a higher value is farther north</li><li><strong>housingMedianAge:</strong> Median age of a house within a block; a lower number is a newer building</li><li><strong>totalRooms:</strong> Total number of rooms within a block</li><li><strong>totalBedrooms:</strong> Total number of bedrooms within a block</li><li><strong>population:</strong> Total number of people residing within a block</li><li><strong>households</strong>: Total number of households, a group of people residing within a home unit, for a block</li><li><strong>medianIncome:</strong> Median income for households within a block of houses (measured in tens of thousands of US Dollars)</li><li><strong>medianHouseValue:</strong> Median house value for households within a block (measured in US Dollars)</li><li><strong>oceanProximity:</strong> Location of the house w.r.t ocean/sea</li></ol><h3>Libraries</h3><p>These were the libraries that were used during this analysis. I used the <strong>“raster”</strong> library to construct the map of California and <strong>“ggplot2”</strong> to plot stacked graphs.</p><pre>library(raster)<br>library(ggplot2)</pre><h3>Data import</h3><pre>fpath&lt;-&quot;/Users/priyanshumadan/Desktop/housing.csv&quot;<br>all_housing&lt;-read.csv(fpath,header=TRUE,stringsAsFactors = FALSE)<br>dim(all_housing)</pre><h3>Data Cleaning</h3><p>I did some basic data cleaning. I replaced <strong>N/A</strong> values with 0.</p><pre>all_housing$total_bedrooms[is.na(all_housing$total_bedrooms)]=0</pre><p><strong><em>Alright, time for some analysis!</em></strong></p><h3>Basic Exploration</h3><p>I initiated the analysis by exploring some basic summary metrics.</p><p><strong>1. Total Households</strong></p><pre>dim(all_housing)<br>sum(all_housing$households)</pre><p>There are 10,310,499 households at 20,640 different locations across California.</p><p><strong>2. Households by Ocean Proximity</strong></p><pre># MAP CREATION</pre><pre>states    &lt;- c(&#39;California&#39;)<br>us &lt;- getData(&quot;GADM&quot;,country=&quot;USA&quot;,level=1)<br>us.states &lt;- us[us$NAME_1 %in% states,]<br>us.bbox &lt;- bbox(us.states)<br>xlim &lt;- c(min(us.bbox[1,1]),max(us.bbox[1,2]))<br>ylim &lt;- c(min(us.bbox[2,1]),max(us.bbox[2,2]))</pre><pre># CREATION OF DATA FRAME TO STORE HOUSEHOLD COUNT BY OCEAN PROXIMITY</pre><pre>household_ocean &lt;- data.frame(matrix(nrow = 5, ncol = 2))<br>colnames(household_ocean) &lt;- c(&quot;Ocean Proximity&quot;,&quot;Household Count&quot;)</pre><pre>household_ocean[,1]&lt;-c(&quot;&lt;1H OCEAN&quot;,&quot;INLAND&quot;,&quot;ISLAND&quot;,&quot;NEAR BAY&quot;,&quot;NEAR OCEAN&quot;)<br>household_ocean[,2]&lt;-c(sum(all_housing$households[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;])<br>                       ,sum(all_housing$households[all_housing$ocean_proximity==&quot;INLAND&quot;])<br>                       ,sum(all_housing$households[all_housing$ocean_proximity==&quot;ISLAND&quot;])<br>                       ,sum(all_housing$households[all_housing$ocean_proximity==&quot;NEAR BAY&quot;])<br>                       ,sum(all_housing$households[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;])<br>                       )</pre><pre># PLOTTING OF BAR GRAPH</pre><pre>barplot( height = household_ocean[,2]<br>         , las = 1<br>         , col = cool_colour$Coolness_Color<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Ocean Proximity&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;proximity&quot;<br>         , ylim = c(0,5000000)<br>         ,names.arg = household_ocean[,1]<br>)</pre><pre># PLOTTING LOCATION POINTS ON THE MAP</pre><pre>plot(us.states, xlim=xlim, ylim=ylim)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;], all_housing$latitude[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;], col = &quot;#F8756D&quot;, cex = .5)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;NEAR BAY&quot;], all_housing$latitude[all_housing$ocean_proximity==&quot;NEAR BAY&quot;], col = &quot;#00BE7D&quot;, cex = .5)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;INLAND&quot;], all_housing$latitude[all_housing$ocean_proximity==&quot;INLAND&quot;], col = &quot;#A3A500&quot;, cex = .5)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;ISLAND&quot;], all_housing$latitude[all_housing$ocean_proximity==&quot;ISLAND&quot;], col = &quot;#03B0F6&quot;, cex = .5)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;], all_housing$latitude[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;], col = &quot;#E76AF3&quot;, cex = .5)</pre><ul><li><em>First few lines of code are for the creation of the California map. Any number of states can be added just by including the name of the state in the state variable.</em></li><li><em>I then constructed a data frame (households_ocean) so as to store the count of households by ocean proximity. This makes the data easier to understand as I won&#39;t have to go back to the original dataset.</em></li><li><em>Finally comes the plotting of location points on the map. The first step was to plot the map of California using “plot” function followed by plotting the points using “points” function and using “latitude” and “longitude” column as attributes for those points.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rBdMSKZpEZtl4xOB.png" /><figcaption><strong>Households by Ocean Proximity</strong></figcaption></figure><p>It can be observed from the graph above (<strong>Households by Ocean Proximity</strong>) that there are more households (4,730,118 households) situated 1 hour away from the ocean (&lt;1H OCEAN) as compared to other areas. It is followed by households (3,127,759) that are situated inland (INLAND ). Though it can be seen from the map that INLAND households are much more widespread as compared to that of other locations making areas closer to the ocean much more densely populated as compared to INLAND.</p><p><strong><em>Let&#39;s confirm this hypothesis by looking at the population data</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jS6V2QdMp4xerD5J.png" /><figcaption><strong>Households by Ocean Proximity</strong></figcaption></figure><p>This was not a surprise. More households mean more people living in that area.</p><p><em>BUT WHY IS THAT? WHY ARE MORE PEOPLE SITUATED AT AREAS THAT ARE 1 HOUR AWAY FROM THE OCEAN AND NOT NEAR THE OCEAN, BAY OR INLAND. LET’S FIND OUT.</em></p><p><strong>3. Households by Median Age</strong></p><pre>age_level &lt;- c(0,5,10,15,20,25,30,35,40,45,50,55)<br>headers &lt;- c(&quot;0 to 5&quot;,&quot;5 to 10&quot;, &quot;10 to 15&quot;, &quot;15 to 20&quot;, &quot;20 to 25&quot;,&quot;25 to 30&quot;,<br>             &quot;30 to 35&quot;,&quot;35 to 40&quot;,&quot;40 to 45&quot;,&quot;45 to 50&quot;, &quot;50 to 55&quot;)<br>all_housing &lt;- transform(all_housing, age_cut = cut(housing_median_age, age_level, labels = headers))</pre><pre>barplot( height = rowsum(all_housing$households,all_housing$age_cut)[,1]<br>         , las = 1<br>         , col = &quot;#52338B&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Age&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,2000000)<br>)</pre><ul><li><em>I wanted to make age group categories as this will help to compress the data and I am not interested in the actual age of the house. Just an age group would be fine to help me understand how old the houses are in those areas.</em></li><li><em>First I had to define the cut values for age that will be used as limits for the age groups. “cut(column, cut groups, labels)” function is then used to make the groups of age. “transform” function creates a new column for age group (age_cut) to “all_housing” dataset.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ORTCGdb5IsrPephO.png" /></figure><p>The above graph tells us the median age of all the households in California. This looks like a normal distribution where most of the households are 15–35 years old. Let’s break it down further by ocean proximity to get a deeper understanding.</p><pre>household_age_1H &lt;- data.frame(matrix(nrow=9136,ncol = 2))<br>colnames(household_age_1H) &lt;- c(&quot;households&quot;,&quot;agecut&quot;)<br>household_age_1H[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;])<br>household_age_1H[,2]&lt;-c(headers[all_housing$age_cut[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;]])</pre><pre>household_age_inland &lt;- data.frame(matrix(nrow=6551,ncol = 2))<br>colnames(household_age_inland) &lt;- c(&quot;households&quot;,&quot;agecut&quot;)<br>household_age_inland[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;INLAND&quot;])<br>household_age_inland[,2]&lt;-c(headers[all_housing$age_cut[all_housing$ocean_proximity==&quot;INLAND&quot;]])</pre><pre>household_age_island &lt;- data.frame(matrix(nrow=5,ncol = 2))<br>colnames(household_age_island) &lt;- c(&quot;households&quot;,&quot;agecut&quot;)<br>household_age_island[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;ISLAND&quot;])<br>household_age_island[,2]&lt;-c(headers[all_housing$age_cut[all_housing$ocean_proximity==&quot;ISLAND&quot;]])</pre><pre>household_age_bay &lt;- data.frame(matrix(nrow=2290,ncol = 2))<br>colnames(household_age_bay) &lt;- c(&quot;households&quot;,&quot;agecut&quot;)<br>household_age_bay[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;NEAR BAY&quot;])<br>household_age_bay[,2]&lt;-c(headers[all_housing$age_cut[all_housing$ocean_proximity==&quot;NEAR BAY&quot;]])</pre><pre>household_age_ocean &lt;- data.frame(matrix(nrow=2658,ncol = 2))<br>colnames(household_age_ocean) &lt;- c(&quot;households&quot;,&quot;agecut&quot;)<br>household_age_ocean[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;])<br>household_age_ocean[,2]&lt;-c(headers[all_housing$age_cut[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;]])</pre><ul><li><em>Same as before, I created data frames for each ocean proximity to store household count for each age group. Each data frame has 2 columns “households and agecut”</em></li></ul><pre>barplot( height = rowsum(household_age_1H$households,household_age_1H$agecut)[,1]<br>         , las = 1<br>         , col = &quot;#F8756D&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Age (&lt;1H OCEAN)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,800000)<br>)</pre><pre>barplot( height = rowsum(household_age_inland$households,household_age_inland$agecut)[,1]<br>         , las = 1<br>         , col = &quot;#A3A500&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Age (INLAND)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,800000)<br>)</pre><pre>barplot( height = rowsum(household_age_island$households,household_age_island$agecut)[,1]<br>         , las = 1<br>         , col = &quot;#03B0F6&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Age (ISLAND)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,800000)<br>)</pre><pre>barplot( height = rowsum(household_age_bay$households,household_age_bay$agecut)[,1]<br>         , las = 1<br>         , col = &quot;#00BE7D&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Age(NEAR BAY)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,800000)<br>)</pre><pre>barplot( height = rowsum(household_age_ocean$households,household_age_ocean$agecut)[,1]<br>         , las = 1<br>         , col = &quot;#E76AF3&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Age (NEAR OCEAN)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,800000)<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6p8Ll9sCkW5ZXGf4.png" /><figcaption>Households by Median Age</figcaption></figure><p>All graphs except “Near Bay” have the more or less same distribution of households with most of them being in the age group of 10–40 years old. This means that the construction of new houses is quite common in these areas.</p><p>Now, If I combine this data of median age of households with the population data. It can be infered/assumed that most of the people living 1hr away from the ocean (&lt;1hr OCEAN) moved there around 15–20 years ago.</p><p>But what intrigues me is the distribution of “Near bay” graph. unlike the other distributions, this graph shows that most of the households in the bay area are more than 50 years old.</p><p><strong><em>BUT WHY?</em></strong></p><p>On doing further research I found out that it is because of San Francisco’s old cultural heritage and art.</p><p><strong>4. Households by Median Income</strong></p><pre>all_housing$median_income&lt;-all_housing$median_income*10000</pre><pre>income_level &lt;- c(0,10000,20000,30000,40000,50000,60000,70000,80000,90000,100000,110000,120000,130000,140000,150000,Inf)<br>headers_income &lt;- c(&quot;0-10k&quot;, &quot;10k-20k&quot;, &quot;20k-30k&quot;,&quot;30k-40k&quot;, &quot;40k-50k&quot;, &quot;50k-60k&quot;,&quot;60k-70k&quot;,&quot;70k-80k&quot;,&quot;80k-90k&quot;,&quot;90k-100k&quot; <br>                    ,&quot;100k-110k&quot;,&quot;110k-120k&quot;,&quot;120k-130k&quot;,&quot;130k-140k&quot;,&quot;140k-150k&quot;,&quot; &gt;150k&quot;)<br>all_housing &lt;- transform(all_housing, income_cut = cut(median_income, income_level, labels = headers_income))<br></pre><pre>household_income_bay &lt;- data.frame(matrix(nrow=2290,ncol = 2))<br>colnames(household_income_bay) &lt;- c(&quot;households&quot;,&quot;incomecut&quot;)<br>household_income_bay[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;NEAR BAY&quot;])<br>household_income_bay[,2]&lt;-c(headers_income[all_housing$income_cut[all_housing$ocean_proximity==&quot;NEAR BAY&quot;]])</pre><pre>household_income_ocean &lt;- data.frame(matrix(nrow=2658,ncol = 2))<br>colnames(household_income_ocean) &lt;- c(&quot;households&quot;,&quot;incomecut&quot;)<br>household_income_ocean[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;])<br>household_income_ocean[,2]&lt;-c(headers_income[all_housing$income_cut[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;]])</pre><pre>household_income_1H &lt;- data.frame(matrix(nrow=9136,ncol = 2))<br>colnames(household_income_1H) &lt;- c(&quot;households&quot;,&quot;incomecut&quot;)<br>household_income_1H[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;])<br>household_income_1H[,2]&lt;-c(headers_income[all_housing$income_cut[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;]])</pre><pre>household_income_inland &lt;- data.frame(matrix(nrow=6551,ncol = 2))<br>colnames(household_income_inland) &lt;- c(&quot;households&quot;,&quot;incomecut&quot;)<br>household_income_inland[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;INLAND&quot;])<br>household_income_inland[,2]&lt;-c(headers_income[all_housing$income_cut[all_housing$ocean_proximity==&quot;INLAND&quot;]])</pre><pre>household_income_island &lt;- data.frame(matrix(nrow=5,ncol = 2))<br>colnames(household_income_island) &lt;- c(&quot;households&quot;,&quot;incomecut&quot;)<br>household_income_island[,1]&lt;-c(all_housing$households[all_housing$ocean_proximity==&quot;ISLAND&quot;])<br>household_income_island[,2]&lt;-c(headers_income[all_housing$income_cut[all_housing$ocean_proximity==&quot;ISLAND&quot;]])</pre><pre>barplot( height = rowsum(all_housing$households,all_housing$income_cut)[,1]<br>         , las = 1<br>         , col = &quot;#52338B&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Income&quot;<br>         , ylim = c(0,3000000)<br>         , space = 0.07<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OJheEdVwFEJwXIpX.png" /><figcaption>Households by Median Income</figcaption></figure><p>This graph talks about the median income of the people living in a household. This will give us an idea of the price/rent of the houses they live in.</p><p>On analysis, it is clear that the median income of most of the households is between $20k to $50k and there are very few households who have their median income above $100K.</p><p>Now, let’s look at this based on ocean proximity.</p><pre>barplot( height = rowsum(household_income_1H$households,household_income_1H$incomecut)[,1][headers_income]<br>         , las = 1<br>         , col = &quot;#F8756D&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (&lt;1H OCEAN)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><pre>barplot( height = rowsum(household_income_inland$households,household_income_inland$incomecut)[,1][headers_income]<br>         , las = 1<br>         , col = &quot;#A3A500&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (INLAND)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><pre>barplot( height = rowsum(household_income_island$households,household_income_island$incomecut)[,1][headers_income]<br>         , las = 1<br>         , col = &quot;#03B0F6&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (ISLAND)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><pre>barplot( height = rowsum(household_income_bay$households,household_income_bay$incomecut)[,1][headers_income]<br>         , las = 1<br>         , col = &quot;#00BE7D&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (NEAR BAY)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><pre>barplot( height = rowsum(household_income_ocean$households,household_income_ocean$incomecut)[,1][headers_income]<br>         , las = 1<br>         , col = &quot;#E76AF3&quot;<br>         , border = NA  # eliminates borders around the bars<br>         , main = &quot;Households by Median Income (NEAR OCEAN)&quot;<br>         , ylab = &quot;count of households&quot;<br>         , xlab = &quot;Age&quot;<br>         , ylim = c(0,1400000)<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l9hVJeXIQnoElJJw.png" /><figcaption>Households by Median Income</figcaption></figure><p>Most of them follow the same trend, having median income in $30K — $40K range except households in inland (INLAND). The median income of households in inland are in the $20k — $30k, which is quite obvious as it is away from the ocean and expense of living is less and hence income is less.</p><h3>Pricing Analysis</h3><p>I wanted to understand the different factors that affect the price of a house</p><blockquote>I found making of the bar plots to be repetative so decided to go for a different visualization method which is easier to understand at the same time less work for me to make these graphs</blockquote><ol><li>Median Price by Ocean Proximity</li></ol><pre>stack_plot &lt;- ggplot(data = all_housing) + geom_bar(map = aes(x = all_housing$value_cut, <br>fill = all_housing$ocean_proximity))</pre><pre>stack_plot + labs(x=&quot;price range&quot;,y=&quot;count of households&quot;,title=&quot;Median price of households&quot;) + <br>labs(colour = &quot;ocean proximity&quot;)</pre><ul><li><em>I used the ggplot library to construct a stack plot. stack plot is particularly useful if you want to show the relationship between 3 parameters.</em></li><li><em>In this case, the x-axis is the range of values (range-cut), the y-axis is the count or frequency (count of households), and the colors filled inside the bars are the ocean proximity.</em> <em>— the second line of code lets you add labels to your stack plot.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fNOFg8NQiaQ3RNf1.png" /></figure><p>It can be seen from the stack plot that most of the houses that are cheap are inland. As we come closer to the ocean the price of the houses increases (green color blocks gets narrower as the price range increases). There are a lot of houses of all price range that are 1 hour away from the ocean (&lt;1h ocean). But there are little to no houses that are in the range of $0-$50k except inland.</p><p>Now I want to know the exact location of these households based on their price.</p><pre>rCols &lt;- heat.colors(12,0.25)<br>brCols &lt;- rCols[all_housing$value_cut]</pre><pre>plot(us.states, xlim=xlim, ylim=ylim,main=&quot;median price by ocean proximity&quot;)<br>points(all_housing$longitude,all_housing$latitude,col=brCols,pch = 18, cex = 0.4)</pre><p><em>- heat.colors(n, alpha) function is used to define the colors for the heat map. “12” is the number of colors I needed and “0.25” is the value of alpha or transparency. “brCols” assigns “rcol” to the “value_cut”</em></p><p><em>- Then I constructed the map using plot function as I did previously and used points function to plot the points on the map. I used “brcol” in the “col” attribute of the function</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/0*7RvLM-DXUa2l50u1" /><figcaption>Median Price by Ocean Proximity (map)</figcaption></figure><p>This map depicts the location of houses based on their prices. The points that are red in color are inexpensive and are mostly located inland as we know from the stack plot. The points that are yellow and expensive. Brighter colors tell us that those areas are densely populated with houses with the same price range. So it can be seen that inland has only red spots. Bay area and areas near the ocean have both yellow and red and colors ranging between yellow and red. this means that these areas have houses in almost all price range.</p><pre>plot(us.states, xlim=xlim, ylim=ylim,main=&quot;median price by ocean proximity (NEAR BAY)&quot;)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;NEAR BAY&quot;],all_housing$latitude[all_housing$ocean_proximity==&quot;NEAR BAY&quot;],col=brCols,pch = 18, cex = 0.4)</pre><pre>plot(us.states, xlim=xlim, ylim=ylim,main=&quot;median price by ocean proximity (NEAR OCEAN)&quot;)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;],all_housing$latitude[all_housing$ocean_proximity==&quot;NEAR OCEAN&quot;],col=brCols,pch = 18, cex = 0.2)</pre><pre>plot(us.states, xlim=xlim, ylim=ylim,main=&quot;median price by ocean proximity (INLAND)&quot;)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;INLAND&quot;],all_housing$latitude[all_housing$ocean_proximity==&quot;INLAND&quot;],col=brCols,pch = 18, cex = 0.2)</pre><pre>plot(us.states, xlim=xlim, ylim=ylim,main=&quot;median price by ocean proximity (ISLAND)&quot;)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;ISLAND&quot;],all_housing$latitude[all_housing$ocean_proximity==&quot;ISLAND&quot;],col=brCols,pch = 18, cex = 1.8)</pre><pre>plot(us.states, xlim=xlim, ylim=ylim,main=&quot;median price by ocean proximity (&lt;1H OCEAN)&quot;)<br>points(all_housing$longitude[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;],all_housing$latitude[all_housing$ocean_proximity==&quot;&lt;1H OCEAN&quot;],col=brCols,pch = 18, cex = 0.2)</pre><pre>legend(legend = 1:12, fill = rCols, &quot;topright&quot;)</pre><p>Constructed the same map for each ocean proximity separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R2pGuRQ_XiACfQLy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bMsoCJvnKmVkVrcB.png" /><figcaption>Median Price by Ocean Proximity</figcaption></figure><blockquote>Though I got a lot of information from this dataset and learned about the San Francisco housing situation, it was not enough to help me understand different factors that effect the pricing in this state. Factors like occupation, travel time to work, school, stores,etc. I will be on a look out to find a better dataset that would help me make this analysis more richer.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70ccf7852123" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/california-housing-analysis-r-70ccf7852123">California Housing Analysis [R]</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Incremental Processing of data [Python]]]></title>
            <link>https://medium.com/priyanshumadan/incremental-processing-of-data-python-44d1dade423f?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d1dade423f</guid>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Mon, 10 Jun 2019 23:30:45 GMT</pubDate>
            <atom:updated>2019-06-11T01:00:32.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jaz_meNgNGqORk6PeV_TRw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@shemul?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Shahadat Shemul</a> on <a href="https://unsplash.com/search/photos/data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>One of the major problem faced during big data processing is memory management. A lot of memory is consumed if one stores the entire file as a variable for analysis. The efficiency of the code decreases and takes a lot of time for the complete execution.</p><p>So to deal with this, incremental processing is done. This means that the rows of data need to be released from the memory before it proceeds to the next data row. This incremental processing is more memory efficient and theoretically unlimited in how much data it can handle.</p><pre>with open(&#39;file_name.txt&#39;) as file:<br>    for line in file:<br>        line = line.rstrip()<br>        line = line.split(&quot;,&quot;)<br>        lines_all.append(line)<br>        if len(line) == 4:      #header of each block<br>            ID = line[0]        # first column of header row (header name)<br>            file[ID]=[]          <br>        else:<br>            file[ID].append(line) #data inside the headers.</pre><p>In the above code, I am storing blocks of data into a dictionary name file and each time I do a calculation, it is done on each block separately. Releasing the previous block of data from the memory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d1dade423f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/incremental-processing-of-data-python-44d1dade423f">Incremental Processing of data [Python]</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inserting rows to data frame at any position [R]]]></title>
            <link>https://medium.com/priyanshumadan/inserting-rows-to-data-frame-at-any-position-r-b1227acde126?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1227acde126</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Mon, 10 Jun 2019 23:26:19 GMT</pubDate>
            <atom:updated>2019-06-10T23:27:24.572Z</atom:updated>
            <content:encoded><![CDATA[<p>While I was extracting text from PDf to a CSV file (<a href="https://medium.com/priyanshumadan/text-cleaning-pdf-to-csv-r-2bbaf1c954fb">Link</a>), I was stuck at a point where I had to insert multiple rows to a data frame at different indexes. Though this seems to be easy I couldn’t find any solution to this online.</p><p>I have a data frame with the title of abstract in each row. Now I wanted to add author names after each title row which is stored as a list. The number of authors may vary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*HB-obcBcJ5kwMe5F" /></figure><p><em>This is the author list with 209 elements and each element has names of different authors who contributed to that abstract.</em></p><p><strong>Let me show you how I did this.</strong></p><p>I used <a href="https://www.rdocumentation.org/packages/tibble/versions/1.4.2">tibble</a> package. Its a package for data frame manipulation.</p><pre>library(tibble)</pre><p><a href="https://www.rdocumentation.org/packages/tibble/versions/1.4.2/topics/add_row">add_row()</a> is a builtin function of <strong>tibble </strong>package that lets you add one row after/before an index.</p><p>Now for this purpose, I used a nested for loop. first for loop will iterate from 1 to the length of the author list (1:209).</p><pre>for (each in 1:length(insert_count$charac_count)) {<br><br>}</pre><p>The second for loop will iterate over the count of elements in each row of the list. For example, the first row of the list has 4 author names. So the Iteration will be from 1 to 4.</p><pre>for (in_row in 1:(insert_count$charac_count[each])) {<br>    <br>  }</pre><p>Now inside this nested for loop is the <strong>add_row()</strong> function.</p><pre>author_insti&lt;-add_row(author_insti,.after = which(author_insti$s.no==each))</pre><p><strong>author_insti</strong> is the data.frame to which I want to add rows to. <strong>.after =</strong> is used to define the index after which I want to add rows. I used <strong>which()</strong> function to define the position based on the serial number &quot;s.no&quot; of the rows.</p><p>The reason I did this because the index of the rows change after row insertion and if I had used just the index, the rows would have been inserted at the same position and would have been a series of empty rows at the beginning.</p><blockquote><strong>The whole code</strong></blockquote><pre>for (each in 1:length(insert_count$charac_count)) {<br>  <br>  for (in_row in 1:(insert_count$charac_count[each]-1)) {<br>    author_insti&lt;-add_row(author_insti,.after = which(author_insti$s.no==each))<br>  }<br>  <br>}</pre><p><strong><em>This is how it looks after inserting rows</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*B6sRzzOPXfnrmh6H.png" /><figcaption>Rows inserted</figcaption></figure><p>now just use simple replacement to add values to these rows.</p><p>The same thing can be done to insert columns by using <a href="https://www.rdocumentation.org/packages/tibble/versions/1.4.2/topics/add_column">add_column()</a> function</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1227acde126" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/inserting-rows-to-data-frame-at-any-position-r-b1227acde126">Inserting rows to data frame at any position [R]</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Text from a PDF into a structured CSV file using R]]></title>
            <link>https://medium.com/priyanshumadan/text-cleaning-pdf-to-csv-r-2bbaf1c954fb?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bbaf1c954fb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[text-analysis]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Mon, 10 Jun 2019 22:33:08 GMT</pubDate>
            <atom:updated>2019-06-10T23:16:20.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting unstructured text from a PDF to CSV using R</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cr-uOKQSVTcuH3gm" /><figcaption>Photo by <a href="https://unsplash.com/@adliwahid?utm_source=medium&amp;utm_medium=referral">Adli Wahid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data extraction and cleaning is very important and critical part of data analysis. The analysis is the easy part. It&#39;s the cleaning and extraction of raw data that takes time. One spends 80%-90% of the time in this process. Once that is done everyting else is quite easy.</p><p>Recently I was given the task by a firm to extract text from a PDF document that consisted of abstract of different research articles in the field of healthcare. Each abstract consisted of the following components:</p><ol><li>Title of the research article</li><li>Authors of the research article</li><li>Institution of Authors</li><li>Abstract body</li></ol><p>I had to extract these components from the PDF file and store the information in an excel format.</p><p><strong>There were two excel files that I had to make:</strong></p><p>With three columns “s.no”, ” abstract title”, ”abstract”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*xapn9Xn_bs41BGrW.png" /><figcaption>Output 1 (“S.no”, ” Abstract title”, ”Abstract”)</figcaption></figure><ol><li>With four columns “S.no”, ”Abstract title”, ”Author”, ”Abstract”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0TmbJ5t6ZJiKLOtT.png" /><figcaption>Output 2(“S.no”, ”Abstract title”, ”Author”, ”Abstract”)</figcaption></figure><p>The first task was to load the PDF file onto R. But after hours of searching online, I found one method to do so (<a href="https://data.library.virginia.edu/reading-pdf-files-into-r-for-text-mining/">link</a>)…<strong>but that didn’t work</strong>. So I had to do something else.</p><p>It is much easier to work on text file as compared to word file in R. So I decided to save this file in <strong>.txt format</strong>. Little did I know, there are a lot of settings that need to be changed when saving a word file to a text file. So after trying out different combination of settings, I choose these that worked best for my purpose (might be different for you, so try out different settings):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*JhRhJ1Mqlvf1Sqt9.png" /><figcaption>saving PDF to .txt</figcaption></figure><p>After saving, “?” were added at the beginning and at the end of the abstract. (denoting the start of a new page in pdf).</p><p><strong>This is how the text file looks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*2YPSzJUXj8KzGMVP.png" /><figcaption>Text File</figcaption></figure><h3>Data Extraction</h3><p>Next step is to find a pattern so that the extraction of text can work for the whole document and not just the first abstract. This is necessary as it will help me apply regular expression to the code and help me decide the flow of my code.</p><p><strong>This is the pattern I found</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*Eb8yu7VE1KvXSW79.png" /><figcaption>The pattern in the text file</figcaption></figure><p><strong>GENERAL FLOW OF ONE ABSTRACT</strong></p><ol><li>Each abstract starts and ends with a “<strong>?</strong>”</li><li>After the first question mark “<strong>?</strong>” comes the <strong>TITLE</strong> of abstract</li><li>After <strong>TITLE,</strong> an empty line(<strong>BLANK</strong>)</li><li>Followed by <strong>AUTHORS</strong> of the Abstract</li><li>After <strong>AUTHORS</strong> is another empty line(<strong>BLANK</strong>)</li><li>Then comes the <strong>INSTITUTIONS</strong> of the <strong>AUTHORS</strong></li><li>Then again an empty line (<strong>BLANK</strong>)</li><li>Followed by the <strong>BODY</strong> of the abstract</li><li>Finally, a “<strong>?</strong>” marking the end of the abstract.</li></ol><ul><li><strong>TITLE: FIRST LINE</strong></li><li><strong>AUTHOR: AFTER FIRST BLANK</strong></li><li><strong>INSTITUTION: AFTER SECOND BLANK</strong></li><li><strong>BODY: AFTER THIRD BLANK</strong></li></ul><p>You will notice a number after each author and a number before each institution. This denotes that the author belongs to the Institute of that particular number.</p><p>Now that we have found the pattern, <strong>LETS START CODING!!</strong></p><p><strong>LOADING THE TEXT FILE</strong></p><pre>directory&lt;-&quot;/Users/priyanshumadan/Desktop&quot; <br>file_name&lt;-file.path(directory,&quot;clean.txt&quot;)<br>doc_lines&lt;-readLines(file_name,encoding = &quot;UTF-8&quot;)</pre><ul><li><em>readLines() function reads each and every line of the text flie and save it as a large character “doc_lines</em></li></ul><p>Next step is to find the positions of “?”. I will use <strong>grep() function</strong></p><pre>marks&lt;-grep(&quot;^\\?&quot;,doc_lines)<br>marks</pre><ul><li><strong><em>“?”</em></strong><em> has meaning in R. So to escape this I used </em><strong><em>“\\”</em></strong><em>. </em><strong><em>“^”</em></strong><em> mean begining with. so the whole regular expression </em><strong><em>“^\\?”</em></strong><em> mean find the lines in doc_lines that start with a </em><strong><em>“?”</em></strong></li></ul><p>Now, I will create a list called <strong>“data”</strong>. Each element of <strong>“data”</strong> will store all lines of an abstract.</p><pre>#created list of abstracts &quot;data&quot;<br>list_element&lt;-1<br>data&lt;-list()<br>for (c in 1:length(marks)) {<br>  fi&lt;-c<br>  en&lt;-c+1<br>  data[[list_element]]&lt;-c(doc_lines[(marks[fi]+1):(marks[en]-1)])<br>  list_element&lt;-list_element+1<br>}</pre><ul><li><em>The for loop will iterate along the length of the “marks” variable.</em></li><li><strong><em>“fi”</em></strong><em> is the first “?” and </em><strong><em>“en”</em></strong><em> is the next “?”</em></li><li><strong><em>“list_element”</em></strong><em> is a variable that will iterate and store abstract in each element.</em></li><li><strong><em>data[[list_element]]&lt;-c(doc_lines[(marks[fi]+1):(marks[en]-1)])</em></strong><em> will store the lines between 2 consecutive “?”</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*-_nK9nhKV7ye9BYg.png" /><figcaption>This is how <strong>“data”</strong> list looks. As mention above each element stores each line of an abstract as a <strong>character</strong>.</figcaption></figure><p>Now I will create a data.frame <strong>“title_body”</strong>. This will store the title of the abstract along with its abstract body.</p><pre>title_body &lt;- data.frame(matrix(nrow=length(data),ncol = 2))<br>colnames(title_body) &lt;- c(&quot;title&quot;,&quot;body&quot;)<br><br>ro&lt;-1<br>for (ro in 1:length(data)) {<br>  start_blank&lt;-(grep(&quot;^[:blank:]*$|^[ ]*$|^\t*$&quot;,data[[ro]])[3])+1<br>  end_blank&lt;-length(data[[ro]])<br>  <br>  title_start&lt;-1<br>  title_end&lt;-grep(&quot;^[:blank:]*$|^[ ]*$|^\t*$&quot;,data[[ro]])[1]<br>  <br>  title_con&lt;-paste(c(data[[ro]][title_start:title_end]),collapse =&quot;&quot;)<br>  title_body$title[ro]&lt;-rbind(title_con)<br><br>  <br>  body_con&lt;-paste(c(data[[ro]][start_blank:end_blank]),collapse =&quot;&quot;)<br>  title_body$body[ro]&lt;-rbind(body_con)<br>  <br>}</pre><p>For loop will be used to iterate along the length of the “data” list so as to extract title and body from each element of data.</p><p>As mention above, the pattern is:</p><ul><li><strong>TITLE: FIRST LINE</strong></li><li><strong>BODY: AFTER THIRD BLANK</strong></li></ul><p>First, let&#39;s talk about the <strong>body of the abstract</strong>.</p><p>So, <strong>start_blank</strong> looks for the third blank in the element after which the body starts and <strong>end_blank</strong> looks for the end of the abstract. Paste() function combines all lines of the body and this is saved in <strong>body_con</strong> as a large character. <strong>body_con</strong> is then added to the <strong>body</strong> column of <strong>title_body</strong>.</p><p>Now the <strong>title of the abstract</strong>.</p><p><strong>title_start</strong> marks the start of the title which is the first line, and <strong>title_end</strong> marks the end of the title part which is the BLANK after the title. paste() function is used to combine all lines of the title (if there are more than one line) and this is stored in <strong>title_con</strong> as a large character. <strong>title_con</strong> is then added to the <strong>title</strong> column of <strong>title_body</strong>.</p><p>NOTE: I forgot to add the s.no column and I realized that later when it was required.</p><p><em>Adding S.no column</em></p><pre><br>title_body$s.no&lt;-NA<br>title_body$s.no&lt;-c(1:length(title_body$s.no))</pre><p>Now I will create a <strong>data frame</strong> called <strong>author_insti</strong> with 4 columns “s.no”, “title”, “author”, “institution”.</p><pre>author_insti &lt;- data.frame(matrix(nrow=length(data),ncol = 4))<br>colnames(author_insti) &lt;- c(&quot;s.no&quot;,&quot;title&quot;,&quot;authors&quot;,&quot;institutions&quot;)<br><br>for (ro2 in 1:length(data)) {<br>  start_blank_au&lt;-(grep(&quot;^[:blank:]*$|^[ ]*$|^\t*$&quot;,data[[ro2]])[1])+1<br>  end_blank_au&lt;-(grep(&quot;^[:blank:]*$|^[ ]*$|^\t*$&quot;,data[[ro2]])[2])<br>  <br>  author_con&lt;-paste(c(data[[ro2]][start_blank_au:end_blank_au]),collapse =&quot;&quot;)<br>  author_insti$authors[ro2]&lt;-rbind(author_con)<br>  author_insti$s.no[ro2]&lt;-ro2<br>}</pre><p>For loop will be used to iterate along the length of the “data” list so as to extract author name from each element of data.</p><p>As mention above, the pattern is:</p><ul><li><strong>AUTHOR: AFTER FIRST BLANK</strong></li></ul><p>So, <strong>start_blank_au</strong> looks for the first blank in the element after which the author&#39;s name starts and <strong>end_blank_au</strong> looks for the end of the author names which is the second blank. Paste() function combines all lines of the authors and this is saved in <strong>author_con</strong> as a large character. <strong>author_con</strong> is then added to the <strong>author</strong> column of <strong>authoe_insti</strong>.</p><p>Now I will create one more data frame <strong>institution_df</strong> that will store just the <strong>institution</strong> of each abstract</p><pre>institutions_df &lt;- data.frame(matrix(nrow=length(data),ncol = 1))<br>colnames(institutions_df) &lt;- c(&quot;institutions&quot;)<br><br>ro3&lt;-1<br>for (ro3 in 1:length(data)) {<br>  start_blank_in&lt;-(grep(&quot;^[:blank:]*$|^[ ]*$|^\t*$&quot;,data[[ro3]])[2])+1<br>  end_blank_in&lt;-(grep(&quot;^[:blank:]*$|^[ ]*$|^\t*$&quot;,data[[ro3]])[3])<br>  <br>  in_con&lt;-paste(c(data[[ro3]][start_blank_in:end_blank_in]),collapse =&quot;:&quot;)<br>  institutions_df$institutions[ro3]&lt;-rbind(in_con)<br>  <br>}</pre><p>As mention above, the pattern is:</p><ul><li><strong>INSTITUTION: AFTER SECOND BLANK</strong></li></ul><p>So, <strong>start_blank_in</strong> looks for the second blank in the element after which the institution&#39;s name starts and <strong>end_blank_in</strong> looks for the end of the institution&#39;s names which is the third blank. Paste() function combines all lines of the institutions and this is saved in <strong>in_con</strong> as a large character and each institution name is separated by <strong>&quot;:&quot;</strong> using <strong>&quot;collapse&quot;</strong> parameter in paste() function. This &quot;:&quot; help me differentiate one institution to another. <strong>in_con</strong> is then added to the <strong>institution</strong> column of <strong>institution_df</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*a45Na0gW4RCkAD0k.png" /><figcaption><strong>institution_df</strong></figcaption></figure><p>Now I will create a list of all the authors of an abstract separated by a <strong>“,”</strong> and I will call this <strong>sep_author_list</strong>. I will basically split large character string in authors column in <strong>author_insti</strong> after every comma”,” using strsplit() function</p><pre>sep_author_list&lt;-list()<br><br>for (aut_cnt in 1:length(data)) {<br>  sep_author_list[[aut_cnt]]&lt;-c(unlist(strsplit(noquote(author_insti$authors[aut_cnt]),&quot;,&quot;)))<br>}</pre><p><em>For loop will be used to iterate along the length of the “data” list.</em></p><p>Now I want to know the number of authors in each abstract. This can be done by counting the number of characters in each element of <strong>sep_author_list</strong>. I will store this count in another data frame called <strong>insert_count</strong> with only one column called <strong>char_count</strong></p><pre>insert_count &lt;- data.frame(matrix(nrow=length(data),ncol = 1))<br>colnames(insert_count) &lt;- c(&quot;charac_count&quot;)<br><br>for (rows in 1:length(data)) {<br>  insert_count$charac_count[rows]&lt;-length(sep_author_list[[rows]])<br>}</pre><p>This is how <strong>inser_count</strong> data frame looks. the <strong>char_count</strong> column has the number of the author in each abstract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*zUdyATN81_vYaolF.png" /><figcaption><strong>inser_count</strong></figcaption></figure><p>I will use this data frame to add rows to <strong>author_insti</strong>. The reason I am doing this so that I can add each individual author to a separate row.</p><pre>for (each in 1:length(insert_count$charac_count)) {<br>  <br>  for (in_row in 1:(insert_count$charac_count[each]-1)) {<br>    author_insti&lt;-add_row(author_insti,.after = which(author_insti$s.no==each))<br>  }<br>  <br>}</pre><p>I have already given an explanation to these lines of code in my <a href="https://www.priyanshumadan.com/posts/insert-rows/">Inserting rows to data frame at any position</a> learning post. Please have a look at that page for a detailed explanation.</p><p>This is how <strong>author_insti</strong> data frame looks now after inserting rows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*EhfbiCZGOTGWz210.png" /><figcaption><strong>author_insti (after adding rows)</strong></figcaption></figure><p>Now that I have added blank rows after each, its time to add individual authors to each row.</p><pre>for (sep in 1:length(insert_count$charac_count)) {<br>  author_insti$authors[which(author_insti$s.no==sep):(which(author_insti$s.no==(sep+1))-1)]&lt;-c(sep_author_list[[sep]])<br>}<br><br>#the authors of the last abstract are not added as the limit is reached, so it needs to be added manually. </pre><pre>author_insti$authors[which(author_insti$s.no==length(data)):length(author_insti$authors)]&lt;-c(sep_author_list[[length(data)]])</pre><p>I have used the s.no column in <strong>author_insti</strong> as my anchor points. What is happening in these lines of code is that I am asking R to insert values (in this case authors in each element of sep_author_list) between two consecutive s.no values.</p><p>For eg., if sep=1. Then I am using sep=1 to search the index of s.no=1 and index of the row that is one before s.no=2. then I am using c(sep_author_list[[sep]]) to add author names to rows between s.no=1 and s.no=2. this continues for all 209 abstracts.</p><p>The shortcoming of this is that the authors of last abstract don’t get added in the column so I have to insert that manually using author_insti$authors[which(author_insti$s.no==length(data)):length(author_insti$authors)]&lt;-c(sep_author_list[[length(data)]])</p><p>This how the <strong>author_insti</strong> data frame looks. you can see all the authors have their own rows. The cells that have just numbers are the authors that are in the previous cell. It denotes that the author belongs to multiple institutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*v3XwEcMDe7TfgkBE.png" /><figcaption><strong>author_insti (after adding author names to each row)</strong></figcaption></figure><p>Now that we are done with authors, we will now work on institutions. most abstracts may have more than one institutions and some might have only one. So we will separate those. one data frame will have only one institution per abstract and the other that has multiple institutions per abstract.</p><p>The reason I am doing this is that single institutions can be added to <strong>author_insti</strong> directly next to their corresponding authors without any matching required.</p><p>The rest will be similar to what we have done before with authors names. A little more work is required when we are dealing with more than one institution per abstract.</p><p>we will now create a data frame <strong>multi_insti</strong> that will have the names of institutions that are more than one per abstract.</p><pre>temp_multi_insti &lt;- data.frame(matrix(nrow=length(data),ncol = 2))<br>colnames(temp_multi_insti) &lt;- c(&quot;s.no&quot;,&quot;institutions&quot;)<br>temp_multi_insti$s.no[1:length(data)]&lt;-c(1:length(data))<br>temp_multi_insti$institutions&lt;-institutions_df$institutions<br><br>multi_insti&lt;-temp_multi_insti[-c(which(ins_char_count$ins_count==1)),]</pre><p>I will do the same thing with <strong>single institutions</strong></p><pre>temp_single_insti&lt;-data.frame(matrix(nrow=length(data),ncol = 2))<br>colnames(temp_single_insti) &lt;- c(&quot;s.no&quot;,&quot;institutions&quot;)<br>temp_single_insti$s.no[1:length(data)]&lt;-c(1:length(data))<br>temp_single_insti$institutions&lt;-institutions_df$institutions<br><br>single_insti&lt;-temp_single_insti[c(which(all_ins_char_count$ins_count==1)),]</pre><p>Now I will insert institution names in <strong>single_insti</strong> to institution column in <strong>author_insti</strong> by matching s.no of both the data frames.</p><pre>for (sin_ins in 1:length(single_insti$s.no)) {<br>  author_insti$institutions[which(author_insti$s.no==single_insti$s.no[sin_ins])]&lt;-single_insti$institutions[sin_ins]<br>}</pre><p>Now that we are done with all the single institutions, let&#39;s work on multiple institutions.</p><p>As I did with the authors I will separate all the institution in an element of <strong>multi_insti</strong> with a <strong>“:”</strong> and save it in a list called <strong>multi_institutions_list</strong></p><pre>multi_institutions_list&lt;-list()<br><br>for (ins_cnt in 1:length(multi_insti$institutions)) {<br>  multi_institutions_list[[ins_cnt]]&lt;-c(unlist(strsplit(noquote(multi_insti$institutions[ins_cnt]),&quot;:&quot;)))<br>}</pre><p>Now I will count the number of institutions in each element of the list by using length function and save the count in the <strong>ins_count</strong> column of <strong>ins_char_count</strong> data frame.</p><pre>ins_char_count &lt;- data.frame(matrix(nrow=length(multi_institutions_list),ncol = 2))<br>colnames(ins_char_count) &lt;- c(&quot;s.no&quot;,&quot;ins_count&quot;)<br>ins_char_count$s.no&lt;-multi_insti$s.no<br><br>for (ins_rows in 1:length(multi_institutions_list)) {<br>  ins_char_count$ins_count[ins_rows]&lt;-length(multi_institutions_list[[ins_rows]])<br>}</pre><p>I will now create a data frame called <strong>all_institutions</strong> with three columns “s.no”, “sub_num”, ”institutions”. I will explain the role of <strong>“sub_num”</strong> later on.</p><p>I will insert all s.no values and then insert rows after every s.no based on the <strong>ins_char_count</strong> count</p><pre>all_institutions &lt;- data.frame(matrix(nrow=length(ins_char_count$s.no),ncol = 3))<br>colnames(all_institutions) &lt;- c(&quot;s.no&quot;,&quot;sub_num&quot;,&quot;institutions&quot;)<br>all_institutions$s.no&lt;-ins_char_count$s.no<br><br>for (each_ins in 1:length(ins_char_count$ins_count)) {<br>  <br>  for (ins_in_row in 1:(ins_char_count$ins_count[each_ins]-1)) {<br>    all_institutions&lt;-add_row(all_institutions,.after = which(all_institutions$s.no==ins_char_count$s.no[each_ins]))<br>  }<br><br>}</pre><p>Now that I have added rows to the data frame for inserting institutions, I will now insert institutions the same way I added authors.</p><pre>for (ins_sep in 1:length(ins_char_count$ins_count)) {<br>  all_institutions$institutions[which(all_institutions$s.no==ins_char_count$s.no[ins_sep]):(which(all_institutions$s.no==ins_char_count$s.no[ins_sep+1])-1)]&lt;-c(multi_institutions_list[[ins_sep]])<br>}<br><br>#the authors of the last abstract are not added as the limit is reached, so it needs to be added manually. <br>all_institutions$institutions[which(all_institutions$s.no==ins_char_count$s.no[length(ins_char_count$s.no)]):length(all_institutions$institutions)]&lt;-c(multi_institutions_list[[length(ins_char_count$s.no)]])</pre><p>Now as I added new rows, there are some blank spaces in the <strong>s.no</strong> column of both <strong>author_insti</strong> and <strong>all_institutions</strong>. I will now fill those too.</p><pre>for (s_num in 1:length(ins_char_count$ins_count)) {<br>  all_institutions$s.no[which(all_institutions$s.no==ins_char_count$s.no[s_num]):(which(all_institutions$s.no==ins_char_count$s.no[s_num+1])-1)]&lt;-ins_char_count$s.no[s_num]<br>}<br><br>all_institutions$s.no[which(all_institutions$s.no==ins_char_count$s.no[length(ins_char_count$s.no)]):length(all_institutions$s.no)]&lt;-ins_char_count$s.no[length(ins_char_count$s.no)]<br><br>for (s_num2 in 1:length(data)) {<br>  author_insti$s.no[which(author_insti$s.no==s_num2):(which(author_insti$s.no==(s_num2+1))-1)]&lt;-s_num2<br>}<br><br>author_insti$s.no[which(author_insti$s.no==length(data)):length(author_insti$s.no)]&lt;-length(data)</pre><p>This is how s.no column should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/0*6D1tW860K-C7U9PJ" /><figcaption>S.no column</figcaption></figure><p><strong>NOW I REALLY ENJOYED DOING WHAT I DID NEXT.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*WlYJClHBPsHcc595" /></figure><p>As you can see the numbers next to author names and numbers before institution names, I am going to extract these numbers using regexec() function. I will save numbers in the authors column to <strong>auth_num</strong> column in <strong>author_inst</strong> and numbers in the institution column to <strong>ins_num</strong> column of <strong>all_institution</strong>.</p><pre>##################################### Extract number from author names###############################<br>author_num&lt;-regexec(&quot;[[:digit:]]+$&quot;,author_insti$authors)<br>author_num<br>auth_num_match_list&lt;-regmatches(author_insti$authors,author_num)<br>auth_num_match_list<br>author_insti$auth_num&lt;-NA<br>author_insti$auth_num&lt;-auth_num_match_list<br>#################################### Extract numbers from institutions names #############################<br>ins_num&lt;-regexec(&quot;^[[:digit:]]+&quot;,all_institutions$institutions)<br>ins_num<br>ins_num_match_list&lt;-regmatches(all_institutions$institutions,ins_num)<br>ins_num_match_list<br>all_institutions$in_num&lt;-NA<br>all_institutions$in_num&lt;-ins_num_match_list</pre><p>Now I have to create a unique ID for both authors as well as Institutions so that I can combine the authors to their corresponding institutions. “sub_num” in both these data frames <strong>author_insti</strong> and <strong>all_institutions</strong> will work as a unique ID.</p><p>This is how it is going to work. I will combine <strong>s.no</strong> to <strong>auth_num</strong> in <strong>author_insti</strong> and to <strong>ins_num</strong> in <strong>all_institution</strong> using paste() function .</p><pre>#################################paste s.no to in_num ################################################<br><br>for (i in 1:length(all_institutions$s.no)) {<br>  all_institutions$sub_num[i]&lt;-paste(as.character(all_institutions$s.no[i]),all_institutions$in_num[[i]],sep = &quot;.&quot;)<br>}<br><br>#################################paste s.no to auth_num ################################################<br><br>author_insti$sub_num&lt;-NA<br><br>for (j in 1:length(author_insti$s.no)) {<br>  author_insti$sub_num[j]&lt;-paste(as.character(author_insti$s.no[j]),author_insti$auth_num[[j]],sep = &quot;.&quot;)<br>}</pre><p><em>for eg. if s.no=1 and auth_num=2 then sub_num=1.2</em></p><p>This is how the sub_num column looks in <strong>all_institution</strong>. Similar is the case in <strong>author_insti</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*yuMcUB36WxIi_p87" /><figcaption>sub_num column</figcaption></figure><p>Now I will match the <strong>“sub_num”</strong> of both the data frames and add institution from <strong>all_institution</strong> to institution column of <strong>author_insti</strong> when <strong>“sub_num”</strong> are the same in both tables.</p><pre>author_insti$institutions&lt;-all_institutions$institutions[match(author_insti$sub_num,all_institutions$sub_num)]</pre><p>After this, I replaced the cells with just numbers with author names. And made necessary changes that had to be done manually by writing a separate code or by making edits to the text file itself.</p><pre>rep_name&lt;-grep(&quot;^[[:digit:]]+&quot;,author_insti$authors)<br>author_insti$authors[rep_name[1:length(rep_name)]]&lt;-author_insti$authors[(rep_name[1:length(rep_name)]-1)]</pre><p>Now finally remove all the number in the author and institution column of <strong>author_insti</strong></p><pre>grep(&quot;[[:digit:]]+$&quot;,author_insti$authors)<br><br>author_insti$authors&lt;-gsub(&quot;[[:digit:]]+$&quot;,&quot;&quot;,author_insti$authors)<br>author_insti$institutions&lt;-gsub(&quot;^[[:digit:]]+&quot;,&quot;&quot;,author_insti$institutions)</pre><blockquote><strong>AND WE ARE DONE!!!!!</strong></blockquote><p>This is the final file. Clean and ready for analysis. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q-5WfRbKSd4EdtOC.png" /><figcaption>Final Output</figcaption></figure><p><strong>LAST THING TO DO IS SAVE THE REQUIRED OUTPUTS AS A CSV FILE</strong></p><pre>write.csv(title_body,&#39;title_and_body_final.csv&#39;)<br>write.csv(author_insti,&#39;author_insti_final.csv&#39;) <br>write.csv(all_institutions,&#39;institute_list.csv&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bbaf1c954fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/text-cleaning-pdf-to-csv-r-2bbaf1c954fb">Extracting Text from a PDF into a structured CSV file using R</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an E-Commerce Product Recommendation Engine in Python]]></title>
            <link>https://medium.com/priyanshumadan/building-an-e-commerce-product-recommendation-engine-in-python-affb004e47c9?source=rss-32a4b20b6ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/affb004e47c9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Priyanshu Madan]]></dc:creator>
            <pubDate>Mon, 03 Jun 2019 22:21:23 GMT</pubDate>
            <atom:updated>2019-06-12T18:08:08.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OBp9ll1f-kGMne_r" /><figcaption>Photo by <a href="https://unsplash.com/@heftiba?utm_source=medium&amp;utm_medium=referral">Toa Heftiba</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I will be talking about different recommendation systems and how I developed a basic product recommendation engine on top of Wayfair’s product data</p><p><strong>Background</strong></p><p>First, we will discuss the different types of recommendation system. There are three types of recommendation system.</p><ol><li><strong>Content-Based Recommendation System:</strong> This type of recommendation system analyze different parameters of the product (product name, brand, price, description, features). This system takes in the product name as input and returns all the similar products based on these parameters.</li><li><strong>User-Based Recommendation System:</strong> This is also known as collaborative filtering. This takes user demographic data, activities, and preferences into consideration. If person A and person B have similar profiles (age, liking, activity, etc) and person A has liked a particular product or has viewed a particular product, then the recommendation system will recommend person B those products that person A had viewed and vise-versa.</li><li><strong>Popularity-Based Recommendation System:</strong> This system keeps track of views, likes, and products bought and recommend those products that are popular in that region by analyzing these parameters.</li></ol><p>Since I do not have access to Wayfair’s user data and other necessary datasets, I will be making content-based recommendation system. I will be using data that is already public and will be scraping their website using a service called <a href="https://www.import.io/">import.io</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*G4ITnEHsvTMoP0GbIfOazA.png" /><figcaption>import.io</figcaption></figure><p>I will only scrape these particular fields <strong>(product name’, ‘product_name_link’, ‘manufacturer’, ‘price’,’original_price’, ‘review count’, ‘review data’, ‘shipping time’, product description’, ‘product data)</strong>. And I will only consider these particular products <strong>(Lamp, Sofa, Cribs)</strong></p><p><strong>Let&#39;s get started</strong></p><blockquote><a href="https://github.com/priyanshu-madan/product-recommendation-engine">Full code and Dataset</a></blockquote><p><strong>Step 1: Import necessary libraries</strong></p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.metrics.pairwise import cosine_similarity<br>from nltk.corpus import stopwords<br>import nltk<br>nltk.download(&#39;stopwords&#39;)<br>%matplotlib inline<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p><strong>Step 2: Import data and clean data</strong></p><pre>df = pd.read_csv(&quot;wayfair_uniq.csv&quot;)<br>df_new=df.iloc[:,[3,4,5,7,9,11,13,15,17,18,19]]<br>df_new[&#39;index&#39;] = df_new.index<br>df_new.shape</pre><p>There are 17209 products and 12 fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nG7ylXUKoDjtas8_.png" /></figure><p>I had to clean the data so that the recommendation system is accurate.</p><p>I removed the “$” sign from prices column and converted it into a “float” object and dropped the old fields.</p><pre>df_new[&#39;original_price&#39;] = df_new.original_price.str.replace(&#39;$&#39;, &#39;&#39;)<br>df_new[&#39;original_price&#39;] = df_new.original_price.str.replace(&#39;,&#39;, &#39;&#39;).astype(float)<br><br>new_price = df_new[&quot;price&quot;].str.split(&quot;;\s\$&quot;, n = 1, expand = True)<br>df_new[&quot;new_price&quot;] = new_price[1]<br>df_new.drop(columns =[&quot;price&quot;], inplace = True)</pre><p>There were a few rows in the price column that were of ($200 — $900) format. I split the string and took the lower value. First I searched for “-” in the string and then applied split function.</p><pre>price_range = df_new[df_new[&quot;new_price&quot;].str.contains(&quot;-&quot;,regex=True)]<br>price_range[&#39;new_price&#39;] = (price_range[&#39;new_price&#39;].str.split(&quot;\s-&quot;, n = 1, expand = True))[0]<br>df_new.loc[price_range.index] = price_range<br>df_new[&#39;new_price&#39;] = df_new.new_price.str.replace(&#39;,&#39;, &#39;&#39;).astype(float)</pre><p>After cleaning the price column, I created price buckets to categorize products based on their price.</p><pre>bins = [0,500,1000,1500,2000,2500,3000,3500,4000,4500,35000]<br>labels = [&quot;&lt;$500&quot;,&quot;$500-$1000&quot;,&quot;$1000-$1500&quot;,&quot;$1500-$2000&quot;,&quot;$2000-$2500&quot;,&quot;$2500-$3000&quot;,&quot;$3000-$3500&quot;,&quot;$3500-$4000&quot;,&quot;$4000-$4500&quot;,&quot;&gt;$4500&quot;]<br>df_new[&#39;price_bracket&#39;] = pd.cut(df_new[&#39;new_price&#39;], bins, labels=labels)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/0*7eYN6vbitiP16kQX" /></figure><p>Then I removed all “NA” values from the required columns.</p><pre>features = [&quot;product_data1&quot;,&quot;product_data2&quot;,&quot;product_descrip&quot;,&quot;manufacturer&quot;]<br><br>for feature in features:<br>df_new[feature] = df_new[feature].fillna(&#39;&#39;)</pre><p>Then I combined all the features into a large string and saved it as “combined_features” column</p><pre>def combine_features(row):<br>try:<br>    return row[&#39;product_data1&#39;] +&quot; &quot;+row[&#39;product_data2&#39;]+&quot; &quot;+row[&quot;product_descrip&quot;]+&quot; &quot;+row[&quot;price_bracket&quot;]+&quot; &quot;+row[&quot;manufacturer&quot;]<br>except:<br>    print(&quot;Error:&quot;, row)<br>    <br>df_new[&quot;combined_features&quot;] = df_new.apply(combine_features,axis=1)</pre><p>To make the system more accurate I removed all the stopwords (a, an, the, for, that, etc) from the column.</p><pre>stop_words = stopwords.words(&#39;english&#39;)<br>df_new[&#39;combined_features&#39;] = df_new[&#39;combined_features&#39;].str.lower().str.split()<br>df_new[&quot;features&quot;]=df_new[&quot;combined_features&quot;].apply(lambda x: [word for word in x if word not in stop_words])<br>df_new[&quot;features&quot;]=df_new[&quot;features&quot;].apply(lambda x: &quot; &quot;.join(x))</pre><p><strong>Step 3: Recommendation Engine model creation</strong></p><p>I then used CountVectorizer() function to calculate count matrix. Count matrix is the number of occurrences of each word in each product feature.</p><pre>cv = CountVectorizer()<br>count_matrix = cv.fit_transform(df_new[&quot;features&quot;])</pre><p>I used “cosine_similarity()” function to calculate the similarity coefficient of one product to another.</p><pre>cosine_sim = cosine_similarity(count_matrix)</pre><p>I then defined 3 functions that will give <strong>product name</strong> and <strong>product URL</strong> from <strong>product index</strong> and vise-versa.</p><pre>def get_title_from_index(index):<br>    return df_new[df_new.index == index][&quot;product_name&quot;].values[0]<br><br>def get_home(index):<br>    return df_new[df_new.index == index][&quot;product_name_link&quot;].values[0]<br><br>def get_index_from_title(title):<br>    return df_new[df_new.product_name == title][&quot;index&quot;].values[0]</pre><p>Now I will take input of the product name.</p><pre>product_user_likes = &#39;Rosalie Sofa&#39;</pre><p>I extracted the index of the product and created a list of similar products and sorted them based on their cosine similarity value.</p><pre>product_index = get_index_from_title(product_user_likes)<br><br>similar_products =  list(enumerate(cosine_sim[product_index]))<br><br>sorted_similar_products = sorted(similar_products,key=lambda x:x[1],reverse=True)</pre><p><strong>Name and URL of the top 50 similar products.</strong></p><pre>i=0<br>for element in sorted_similar_products:<br>    print (get_title_from_index(element[0]),get_home(element[0]))<br>    i=i+1<br>    if i&gt;50:<br>        break</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vNM-qtPR7u9aGyin.png" /><figcaption><strong>List of all recommended Products</strong></figcaption></figure><p><strong>Checking the product links</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S5y8G1fq6tlBme4u.png" /><figcaption>The product I searched for : &#39;Rosalie Sofa&#39;</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jYz0gtXFGYwqtfvC.png" /><figcaption>First recommended product</figcaption></figure><p><strong>Products are similar to each other. This recommendation system is working.</strong></p><p><strong>Next Steps</strong></p><ul><li>Next step would be to gather data such as product likes, clicks, user demographics, preferences, search words, etc, to make the system more robust.</li><li>Take sentence format and structure into consideration and remove common terms.</li><li>Use visualization to better understand the recommendation algorithm.</li></ul><p><strong>Citations</strong></p><p><a href="https://www.youtube.com/watch?v=XoTwndOgXBM"><em>Building a Movie Recommendation Engine | Machine Learning Projects</em></a></p><p><a href="https://www.wayfair.com/furniture/cat/sofas-sectionals-loveseats-c46093.html"><em>Wayfair product catalog</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=affb004e47c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/priyanshumadan/building-an-e-commerce-product-recommendation-engine-in-python-affb004e47c9">Building an E-Commerce Product Recommendation Engine in Python</a> was originally published in <a href="https://medium.com/priyanshumadan">Priyanshu Madan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>