<?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 Svideloc on Medium]]></title>
        <description><![CDATA[Stories by Svideloc on Medium]]></description>
        <link>https://medium.com/@sam_videlock?source=rss-2a72b07d5910------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ZPvQrlUC8g-77gnnIdsCZA.jpeg</url>
            <title>Stories by Svideloc on Medium</title>
            <link>https://medium.com/@sam_videlock?source=rss-2a72b07d5910------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:26:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sam_videlock/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[Accessing the Twitter API with Tweepy]]></title>
            <link>https://medium.com/analytics-vidhya/accessing-the-twitter-api-with-tweepy-8421329afc5c?source=rss-2a72b07d5910------2</link>
            <guid isPermaLink="false">https://medium.com/p/8421329afc5c</guid>
            <category><![CDATA[twitter-api]]></category>
            <category><![CDATA[tweepy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Svideloc]]></dc:creator>
            <pubDate>Fri, 14 Feb 2020 15:07:27 GMT</pubDate>
            <atom:updated>2020-02-15T11:53:15.181Z</atom:updated>
            <content:encoded><![CDATA[<p>Twitter collects 12 terabytes of data per day, which is roughly 4.3 petabytes per year, which is a lot of data. 456,000 tweets per minute in fact. Not all of this data is available to the public, but it turns out that a surprising amount is. There are a few different ways to access this data, but the one that I found to be the simplest for me is accessing the Twitter API using the package <a href="http://docs.tweepy.org/en/v3.5.0/api.html">Tweepy</a>.</p><p>Through this package, user data or specific tweet data can be easily accessed and brought into python for easy analysis. This post will serve to walk you through the steps of what you need to do in order to access the Twitter API.</p><h4><strong>1. Apply for Access to the Twitter API &amp; Getting Started</strong></h4><p>Prior to using the Twitter API, you will need to be granted access. Follow these steps.</p><ol><li>Create a <a href="https://twitter.com/home">Twitter</a> account (if you don’t already have one).</li><li>Head to the <a href="https://developer.twitter.com/en/apply-for-access">developer Twitter site</a> and apply for a developer account. It took Twitter about a day and a half to approve my application.</li><li>Once approved, you will have to set up your own Dev Environment, and then you will be able to get started with accessing the API.</li></ol><h4>2. Get Tokens &amp; Secret Keys/Access them in Python</h4><p>In order to access the API, you will need 4 different tokens/secret keys which you can find in the “Keys and tokens” tab in your developer environment.</p><p>Let’s take a look at this in code by importing the necessary libraries. I save my tokens in JSON files on my computer in order to keep them hidden.</p><pre>import json </pre><pre># Define a function to open the json<br>def get_keys(path):<br>    with open(path) as f:<br>        return json.load(f)</pre><pre># Using the function to open and load all keys in that file <br>access_token_get = get_keys(&quot;/home/twitter_access_token.json&quot;)<br>access_secret_get = get_keys(&quot;/home/twitter_secret_access_token.json&quot;)<br>consumer_key_get = get_keys(&quot;/home/twitter_api_consumer_key.json&quot;)<br>consumer_secret_get = get_keys(&quot;/home/twitter_api_secret_consumer_key.json&quot;)</pre><pre># Setting tokens/keys as variables<br>ACCESS_TOKEN = list(access_token_get.values())[0]<br>ACCESS_SECRET = list(access_secret_get.values())[0]<br>CONSUMER_KEY = list(consumer_key_get.values())[0]<br>CONSUMER_SECRET = list(consumer_secret_get.values())[0]</pre><p>Now each of the tokens/keys are stored in variables. We are now ready to start using <a href="http://docs.tweepy.org/en/v3.5.0/api.html">Tweepy</a> to get some data.</p><h4>3. Use Tweepy to Grab Data</h4><p>Tweepy is a free Twitter library that provides access to the entire twitter RESTful API methods. I would strongly recommend going to the documentation, as different methods access different types of data, and depending on your needs, one may be better to use over another. For today’s purposes, I am going to demonstrate getting a specific user’s data using the “get_user” method. Specifically, let’s look at Donald Trump&#39;s twitter for fun.</p><pre>#Tweepy Package<br>import tweepy</pre><pre>#Connecting to the API<br>auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)<br>auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)<br>api = tweepy.API(auth)</pre><pre>#Accessing my account information<br>user = api.get_user(screen_name = &#39;realDonaldTrump&#39;)<br>print(user)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*mcXbjPDSvb7SpCXBX7VSnA.png" /></figure><p>And in just a few lines of code, you have quite a bit of user data. Above is a sample of some of the user data that is captured when using the ‘get_user’ method. Now let’s parse through a few parts of the data. Tweepy has made it really easy to grab specific data in this API — let’s look at a few:</p><pre>print(&#39;Total # of Statuses by this User:&#39;, user.statuses_count)<br>print(&quot;User&#39;s Bio:&quot;, user.description)<br>print(&quot;Date Account Created:&quot;, user.created_at)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*8uAPyKx7n6-m6hSQDDj8qA.png" /></figure><p>Great, but now let’s look at how to get the user&#39;s actual tweet data using the ‘user_timeline’ method. You just need two arguments for this, the user and the number of tweets you want. Let’s grab Trump’s 10 most recent tweets:</p><pre>user_tweets = api.user_timeline(screen_name = &#39;realDonaldTrump&#39;, count = 10)</pre><pre>#Print the 5th tweet<br>print(&#39;Tweet 5:&#39;, user_tweets[5].text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*yrxS37bdprcb7O4M9u40Nw.png" /></figure><p>There you have it. Now you should be able to access Twitter user data as well as specific tweets from users. In order to get this data into easily eval methods, you will have to do some loops, but overall this should help you at least gain access to Twitter data using the package Tweepy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8421329afc5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/accessing-the-twitter-api-with-tweepy-8421329afc5c">Accessing the Twitter API with Tweepy</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Selection Methods for Data Science (just a few)]]></title>
            <link>https://medium.com/analytics-vidhya/feature-selection-methods-for-data-science-just-a-few-fca3086eb445?source=rss-2a72b07d5910------2</link>
            <guid isPermaLink="false">https://medium.com/p/fca3086eb445</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Svideloc]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 19:48:45 GMT</pubDate>
            <atom:updated>2020-02-03T08:20:45.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*VtEDMGhLiENNabmLdNrwBg.jpeg" /></figure><h4>Why Feature Selection Matters</h4><p>Before we get started, let’s look into why feature selection should be a part of your models. There are two main reasons for feature selection. First, simpler models are (usually) better. They are easier to understand and scale, and they will be cheaper to run in the long term. By reducing the number of features through feature selection, you are able to identify the important features that the model needs to perform well while decreasing the size of your overall data set. Second, you can cause over-fitting with too many features, meaning your model is learning very well on the training data set but does not do so well on new data that it has not seen before.</p><p>Some basic feature selection methods can use a simple Pearson Correlation or the Chi-Squared method, but we will focus on a few others for the purposes of this post.</p><h3>Methods</h3><h4>1. <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html">Recursive Feature Elimination</a> (RFE)</h4><p>RFE aims to “select features by recursively considering smaller and smaller sets of features.” Essentially this method trains the model on the original number of features, and an importance is given to each feature. The least important features are kicked out, and then the process is repeated to a specified number of features. See Figure 1 for a basic understanding of how RFE is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*QLJIAU2bT92WN6Mpln-tqQ.png" /><figcaption>Figure 1: Recursive Feature Elimination Methodology</figcaption></figure><h4>Example</h4><p>We will look at the sklearn breast cancer data-set for a simple model. My full code can be found on my GitHub by clicking <a href="https://github.com/svideloc/Feature-Selection-Blog">here</a>, but I will only show parts of the code for purposes of this blog.</p><p>Let’s look at the code for logistic regression without recursive feature selection.</p><pre>#No Feature Selection<br>lr = LogisticRegression(class_weight = &#39;balanced&#39;, solver = &#39;lbfgs&#39;, random_state=42, n_jobs=-1, max_iter=500)</pre><pre>lr.fit(X_train, y_train)<br>y_guess = lr.predict(X_train)<br>y_score = lr.predict(X_test)</pre><p>Now let’s look at how it looks with RFE:</p><pre>from sklearn.feature_selection import RFE<br>rfe = RFE(lr, n_features_to_select=7)<br>rfe.fit(X_train, y_train)<br>y_guess = rfe.predict(X_train)<br>y_score = rfe.predict(X_test)</pre><p>Let’s look at the results of these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*duwknIpNPED_txInaNnOVA.png" /><figcaption>Original Model Vs. RFE Selected Features Model</figcaption></figure><p>From here you can see that we actually score a bit higher with the RFE version, likely due to throwing out a bit of noise in the data. Also, the RFE model only used 7 features which is much more efficient than the original model.</p><p><strong>Benefits</strong></p><p>This method should work well for most linear type models and will run relatively quickly, which is a bonus. RFE is also computationally less complex than the next feature selection methods that we will see.</p><p><strong>Drawbacks</strong></p><p>Note the parameter ‘n_reatures_to_select.’ RFE is not the smartest feature selection method, so you need to tell the model how many features you want to select. It will run its elimination until it uses the number of features you specified. This means you have to adjust this number a bit to see where the feature sweet spot is, which is how I got 7 features. You could also write a for loop for this to try different numbers of features!</p><p>If you don’t specify a number of features, RFE will aim to remove half of the features. This can be problematic because you could be eliminating too many features or not enough. That is why it is imperative that you choose parameters mindfully.</p><h4>2. <a href="http://rasbt.github.io/mlxtend/user_guide/feature_selection/SequentialFeatureSelector/">Sequential Feature Selector</a> (SFS)</h4><p>From the documentation: SFA’s “remove or add one feature at a time based on the classifier performance until a feature subset of the desired size <em>k</em> is reached,” k being the number of features which will be less than the original dimensional feature space, d. In Figure 2 below, the model first runs each feature as its own model and then chooses Feature 2 as the best feature. From there it then pairs Feature 2 with each other feature and determines that 2 and 3 perform best. It groups them and adds in each feature again, and sees that 2, 3, and 1 have the best model. It will keep iterating in this manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*GtT1JXyPL7LNHa9EVrtcfg.png" /><figcaption>Figure 2: Sequential Feature Selection Methodology</figcaption></figure><h4>Example</h4><p>Once again, let’s look at the same example, but this time we will use Sequential Feature Selection.</p><pre># Sequential Feature Selection<br>from mlxtend.feature_selection import SequentialFeatureSelector<br>sfs = SequentialFeatureSelector(lr, k_features=&#39;best&#39;, forward = False, n_jobs=-1)</pre><pre>sfs.fit(X_train, y_train)</pre><pre>features = list(sfs.k_feature_names_)<br>lr.fit(X_train[features], y_train)<br>y_score = lr.predict(X_test[features])</pre><p>Let’s look at the results of this method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*AhoyPCWYNE28NQiCw133Yg.png" /><figcaption>Original Model vs. SFS Selected Features Model</figcaption></figure><p>Okay, so we eliminated 7 features and got a slightly worse score using SFS. However, I did not have to manually try and optimize the number of features to run this like in RFE, so we have a slightly more scale-able model now.</p><p><strong>Benefits</strong></p><p>Run time for SFS is a little longer than RFE but is manageable. The main benefit is that this method chooses on its own and can be more intelligent than RFE. If you are lazy than SFS does a little bit more thinking than RFE.</p><p><strong>Drawbacks</strong></p><p>The user has a little less control with this method and can be prone to not selecting the absolute best combination of features as we saw in the above example. Nonetheless, it will still reduce down the dimentionality of your data-set fairly well.</p><h4>2. <a href="http://rasbt.github.io/mlxtend/user_guide/feature_selection/ExhaustiveFeatureSelector/">Exhaustive Feature Selector</a> (EFS)</h4><p>Exhaustive feature selection will be the most robust of the three methods covered in this blog. This is a brute-force evaluation of each feature subset meaning that it tries every possible combination of features and chooses the best performing model. In Figure 3, we have four features. EFS then tries each possible combination using those features, and in the diagram finds that Features 1, 3, and 4 had the best model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*5uszHOfy1CaZz8OOzXNEwA.png" /><figcaption>Figure 3: Exhaustive Feature Selection Methodology</figcaption></figure><p><strong>Benefits</strong></p><p>If you have the computing power, you are sure to optimize your feature selection using Exhaustive Feature Selection. However, I have not used this method in practice due to the time it takes to run. It may also be useful if you do a simpler feature selection method to reduce your features and then try this when you have much fewer features in your data-set.</p><p><strong>Drawbacks</strong></p><p>As stated earlier, EFS will take a lot of computing power. For just a four feature model, this method requires the model to be run 15 times, as you can see in Figure 3. As the number of features increases, this will turn into an extreme amount of models.</p><p>For our 30 feature breast cancer data-set example, this means that the model will have to try 107,3741,823 different combinations (2³⁰-1). This is probably not a good idea!</p><p>Note that you can specify a maximum number of features to use as a parameter when using this method, but the model will still have many iterations to run through.</p><h3>Conclusion</h3><p>In Data Science, there is never a one size fits all solution to a problem, and with feature selection that holds true. The methods outlined in this post serve to provide a few options that may be useful to try and eliminate excessive features in your models, but there are countless other ways to try and reduce features as well. It is also very reasonable to use a combination of many methods as you are adjusting models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fca3086eb445" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/feature-selection-methods-for-data-science-just-a-few-fca3086eb445">Feature Selection Methods for Data Science (just a few)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Target Encoding Vs. One-hot Encoding with Simple Examples]]></title>
            <link>https://medium.com/analytics-vidhya/target-encoding-vs-one-hot-encoding-with-simple-examples-276a7e7b3e64?source=rss-2a72b07d5910------2</link>
            <guid isPermaLink="false">https://medium.com/p/276a7e7b3e64</guid>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Svideloc]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 14:01:02 GMT</pubDate>
            <atom:updated>2020-01-20T04:50:17.658Z</atom:updated>
            <content:encoded><![CDATA[<p>For machine learning algorithms, categorical data can be extremely useful. However, in its original form, it is unrecognizable to most models. In order to solve this problem, we can use different “encoding” techniques to make our categorical data legible.</p><p>In this post, we will cover two common encoding techniques used in data science models — <a href="https://contrib.scikit-learn.org/categorical-encoding/targetencoder.html">Target Encoding</a> and <a href="https://contrib.scikit-learn.org/categorical-encoding/onehot.html">One-hot Encoding</a>.</p><h3>Target Encoding</h3><p>From the documentation linked above, Target Encoding is defined as the process in which</p><blockquote>“features are replaced with a blend of posterior probability of the target given particular categorical value and the prior probability of the target over all the training data.”</blockquote><h4>Example — Target Encoding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*W77md1OC9HSuAFy9b0LEIw.png" /><figcaption>Table 1: Dataframe With Target Encoded Animal Values</figcaption></figure><p>To better understand what this means, let’s look at an example. In Table 1, we have categorical data in the ‘Animal’ column, and we have our binary target in the ‘Target’ column. In the final column, we have the encoded animal values. So how did we get there?</p><ol><li>Group the data by each category and count the number of occurrences of each target (Table 2).</li><li>Next, calculate the probability of Target 1 occurring given each specific ‘Animal Group.’ When we do this we get the following values in Table 2:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*ldULQ2FIPhkxIo56YObrfg.png" /><figcaption>Table 2: Simplified Table to Show how Target Encoding is Calculating the Probability</figcaption></figure><p>3. Finally, add back in the new column, which gives the probability value of each Animal Group. This is shown in the first dataframe (Table 1). Now you have a numerical value that represents the ‘Animal’ feature that can be recognized by machine learning algorithms.</p><p>Note that when you do target encoding in sklearn, your values may be slightly different than what you get with the above methodology. This is because we have only taken into account the posterior probability so far. Sklearn also looks at the prior probability, which in this case would be the probability of the target being 1. In this case, this probability is 0.5 since we have the target equal to 1 half of the time. Sklearn then uses this metric to help smooth out the encoded value so as to not give too much weight to the target encoded feature which is dependent on the target.</p><h4>What This Looks Like in Code</h4><p>In the below code, the ‘category_encoders’ library is used to do the target encoding the fast way (not manually, as explained above).</p><ol><li>Import Libraries</li></ol><pre>import pandas as pd<br>from category_encoders import TargetEncoder</pre><p>2. Target Encode &amp; Clean DataFrame</p><pre>encoder = TargetEncoder()<br>df[&#39;Animal Encoded&#39;] = encoder.fit_transform(df[&#39;Animal&#39;], df[&#39;Target&#39;])</pre><p>This will output the dataframe found in Table 1. This can also be iterable among multiple categorical features.</p><h4>Benefits of Target Encoding</h4><p>Target encoding is a simple and quick encoding method that doesn’t add to the dimensionality of the dataset. Therefore it may be used as a good first try encoding method.</p><h4>Limitations of Target Encoding</h4><p>Target encoding is dependent on the distribution of the target which means target encoding requires careful validation as it can be prone to overfitting. This method is also dataset-specific and will only show significant improvements some of the time.</p><h3>One-hot Encoding</h3><p>One-hot encoding is easier to conceptually understand. This type of encoding simply “produces one feature per category, each binary.” Or for the example above, creating a new feature for cat, dog, and hamster. In the column cat, for example, we show that a cat exists with a 1, and it doesn’t exist with a 0. Let’s look at the same example to make more sense of this:</p><h4>Example — One-hot Encoding</h4><p>Using the same data as above when we one-hot encode, our data will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*kz_RX5EZGXDT_gmgETtdyA.png" /><figcaption>Table 3: One-hot Encoded Dataframe</figcaption></figure><p>Notice now we have three new columns: ‘isCat’, ‘isDog’, and ‘isHamster.’ Each ‘1&#39; signifies that the feature contains the animal in the feature title. If there is a 0, then we don’t have that animal. Once again, we now have new features that a machine learning algorithm can interpret.</p><p>Let’s look at the steps to get here.</p><ol><li>Import Packages</li></ol><pre>import pandas as pd<br>from sklearn.preprocessing import OneHotEncoder <br>from sklearn.preprocessing import LabelEncoder</pre><ol><li>Label Encode (give a number value to each category, i.e. cat = 0) — shown in the ‘Animal Encoded’ column in Table 3.</li></ol><pre>le = LabelEncoder()<br>df[&#39;Animal Encoded&#39;] = le.fit_transform(df.Animal)</pre><ol><li>One-hot Encode &amp; Clean Dataframe</li></ol><pre>encoder = OneHotEncoder(categories = &#39;auto&#39;)</pre><pre>X = encoder.fit_transform(<br>    df[&#39;Animal Encoded&#39;].values.reshape(-1,1)).toarray()</pre><pre>dfonehot = pd.DataFrame(X)<br>df = pd.concat([df, dfonehot], axis =1)<br>df.columns = [&#39;Animal&#39;,&#39;Target&#39;,&#39;Animal Encoded&#39;,<br>                     &#39;isCat&#39;,&#39;isDog&#39;,&#39;isHamster&#39;]</pre><p>This will output the full dataframe shown in Table 3. Now you have 3 new features that can be understood by a machine learning algorithm.</p><h4>Benefits of One-hot Encoding</h4><p>One-hot encoding works well with nominal data and eliminates any issue of higher categorical values influencing data, since we are creating each column in the binary 1 or 0.</p><h4>Limitations of One-hot Encoding</h4><p>One-hot encoding can create very high dimensionality depending on the number of categorical features you have and the number of categories per feature. This can become problematic not only in smaller datasets but also potentially in larger datasets as well. Combining PCA with one-hot encoding can help reduce that dimensionality when running models. One-hot encoding can also be problematic in tree-based models. See <a href="https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/">here</a> for further discussion.</p><h3>Conclusion</h3><p>There are many different types of encoding. I recommend exploring other options as you dive into specific datasets. With that said, these two are common approaches that can help you make use of the categorical features that exist within datasets.</p><p>You can access the code I used for this blog on my <a href="https://github.com/svideloc/EncodingBlogPost">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=276a7e7b3e64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/target-encoding-vs-one-hot-encoding-with-simple-examples-276a7e7b3e64">Target Encoding Vs. One-hot Encoding with Simple Examples</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn Right in 2 Miles: Finding Distances Using the Google Maps API and Pandas]]></title>
            <link>https://medium.com/analytics-vidhya/turn-right-in-2-miles-finding-distances-using-the-google-maps-api-and-pandas-fef8554f0b7d?source=rss-2a72b07d5910------2</link>
            <guid isPermaLink="false">https://medium.com/p/fef8554f0b7d</guid>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-maps-api]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <dc:creator><![CDATA[Svideloc]]></dc:creator>
            <pubDate>Thu, 19 Dec 2019 17:58:09 GMT</pubDate>
            <atom:updated>2020-01-18T15:49:19.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turn Right in 2 Miles: Simple Method to Find Distance Using the Google Maps API and Pandas</h3><h3>Background</h3><p>Enormous amounts of location data are generated every day. Uber, Lyft, Google Maps, Yelp, Lime and many others all use and generate this data on their various platforms. There’s a wealth of information waiting to be accessed, but you may find yourself needing some guidance on how to work with and gain insights from this data.</p><p>In this post, we will use the Google Maps API to identify the distance between a pick-up and drop-off location, given latitude and longitude.</p><p>We will look at the following dataframe to calculate the distances between the pick-up and drop-off:</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*y7b3rmviVuxY7IPHEHsUbQ.png" /></figure><p>Before accessing the API, you will need to first <a href="https://developers.google.com/maps/documentation">create an account</a> with the Google Maps Platform.</p><p>Note that you will have to put payment information in, but you get $200 in monthly credit for free access. Additional pricing can be found <a href="https://cloud.google.com/maps-platform/pricing/sheet/?_ga=2.244908933.1023964652.1576690143-691402014.1576690143">here</a> if you need to access the API more. Look to the Distance Matrix cell.</p><p>I am using data from Kaggle, which can be found <a href="https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data">here</a>.</p><h3>Why Use Google Maps API?</h3><p>Depending on what you are doing with your data, you may want to calculate the distance differently. Below, I will discuss two popular ways to calculate distance using triangles (Pythagorean theorem). The Google Maps API gives you the actual driving distance and therefore can be more precise if your models require that kind of precision.</p><p>Let’s look at an example for the Distance from New York to Houston using each method:</p><p><strong>Euclidean Distance</strong></p><p>Euclidean distance is calculated as the hypotenuse of a right triangle, just like in the Pythagorean theorem. This is simply a direct path from point A to point B. In the image below, this would be the black line. The euclidean distance is roughly 1,417 miles. Although not perfect, this may be a good estimate for flight distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*yG8UYjGvefnFmFow8XOWYg.png" /></figure><p><strong>Manhattan Distance</strong></p><p>Manhattan distance is calculated as the sum of the sides of the right triangle. This is shown with the red lines in the image. The Manhattan distance is about 2,015 miles from New York to Houston. This method has its problems but could be a good estimate in grid-based cities.</p><p><strong>Google Maps API Distance</strong></p><p>The Google Maps API gives us the actual driving distance, just like what you would get if you were to map from New York to Houston in your Google Maps phone app. In the image, the blue line is the Google Maps API distance and is roughly 1,630 miles. This can be useful if you have Uber data or any number of other data for which you want to know the driving distance.</p><p>Depending on your purposes, each method has its advantages and disadvantages, but we will cover accessing the Google Maps API distance in the code below.</p><p>It is important to understand that this API follows the rules of the road. Therefore your latitudes and longitudes need to be as precise as possible. If you are off by just 10 feet, the API might think you are on the other side of the road and miscalculate the driving distance.</p><h3>Python Code</h3><h4>1. Packages to Import</h4><ul><li><strong>pandas</strong>: data analysis tool in Python. These can be used to manipulate data and create dataframes.</li><li><strong>json</strong>: data interchange package. I use this to access my stored API key in a .json file; this is to keep my API key private.</li><li><strong>requests:</strong> makes requests using the most common HTTP methods.</li></ul><pre>import json<br>import requests<br>import pandas as pd</pre><h4>2. Access the API with Test Try</h4><p>First, you will need to access your API key. I store my API in different .json files on my computer and access them with the following code (if you have a preferred way of accessing your API key, then use that.):</p><pre>def get_keys(path):<br>    with open(path) as f:<br>        return json.load(f)</pre><pre>API_key = get_keys(&quot;/Users/Documents/google_key.json&quot;)</pre><pre>google_key = list(API_key.values())[0]</pre><p>Bring in the API Url and call a test (I typically start by doing a test in Postman, and then move to my Jupyter Notebook after). The output is below the block of code:</p><pre>url = f&quot;<a href="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&amp;origins=40.6655101,-73.89188969999998&amp;destinations=40.6905615%2C-73.9976592&amp;key={google_key">https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&amp;origins=40.6655101,-73.89188969999998&amp;destinations=40.6905615%2C-73.9976592&amp;key={google_key</a>}&quot;</pre><pre>r = requests.get(url)<br>data = r.json()<br>data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*tedDNmU3l-H0Y2I2eOi7yw.png" /></figure><p>Okay, looks like the API was successful. We can see the information in the output above. For this particular example, I am only interested in the parameter that shows me ‘6.5 mi’ — or the distance of the trip. We can access that specific item with the following code:</p><pre>data[&#39;rows&#39;][0][&#39;elements&#39;][0][&#39;distance&#39;][&#39;text&#39;]</pre><p>This will output the string: ‘6.5 mi’</p><p>We will deal with the string later.</p><h4>3. Accessing API for All Values in the DataFrame</h4><p>Now that we know how to access the API, we will want to do this for each row in the dataframe. I first turn each lat/long into their own list and loop through the API for each of the list items.</p><pre>lat_origin = df[&#39;pickup_latitude&#39;].tolist()<br>long_origin = df[&#39;pickup_longitude&#39;].tolist()<br>lat_destination = df[&#39;dropoff_latitude&#39;].tolist()<br>long_destination = df[&#39;dropoff_longitude&#39;].tolist()</pre><pre>distance = []<br>for i in range(len(long_destination)):<br>    url = f&quot;<a href="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&amp;origins={lat_origin[i]},{long_origin[i]}&amp;destinations={lat_desitnation[i]}%2C{long_destination[i]}&amp;key={google_key">https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&amp;origins={lat_origin[i]},{long_origin[i]}&amp;destinations={lat_destination[i]}%2C{long_destination[i]}&amp;key={google_key</a>}&quot;<br>    r=requests.get(url)<br>    data = r.json()<br>    try:<br>        distance.append(data[&#39;rows&#39;][0][&#39;elements&#39;][0][&#39;distance&#39;][&#39;text&#39;])<br>    except:<br>        pass</pre><pre>distance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFhfqR2NEuaRgP5Fc4GbWg.png" /></figure><p>From the output above you can see that we now have a list of distances in the order that we accessed them from the API.</p><h4>4. Cleaning the Data &amp; Adding to Dataframe</h4><p>Finally, we will remove the ‘ mi’ from each item in the list and then place the new list into our original dataframe.</p><pre>distance2 = []<br>for i in range(len(distance)):<br>    distance2.append(float((distance[i].replace(&#39; mi&#39;, &#39;&#39;))))</pre><pre>df[&#39;Distance_in_Miles&#39;] = distance2</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Khc2Q67zjFUNnTqC91y7-w.png" /></figure><p>From above, you can see the original dataframe with the lat/long data, as well as the new column that we created, which shows the driving distance of each trip.</p><p>There are many ways to find distance between locations, but it is imperative that you understand which way will add the most value to a project or model that you are working on. The Google Maps API can be a useful tool in order to find the driving distance between two points.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fef8554f0b7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/turn-right-in-2-miles-finding-distances-using-the-google-maps-api-and-pandas-fef8554f0b7d">Turn Right in 2 Miles: Finding Distances Using the Google Maps API and Pandas</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>