<?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 Yue Weng Mak on Medium]]></title>
        <description><![CDATA[Stories by Yue Weng Mak on Medium]]></description>
        <link>https://medium.com/@yueweng.mak?source=rss-37344f01892b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ao1aU0PsWUnwgbg8</url>
            <title>Stories by Yue Weng Mak on Medium</title>
            <link>https://medium.com/@yueweng.mak?source=rss-37344f01892b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:50:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yueweng.mak/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[3 Different Techniques to build Recommender Systems for Restaurants based in San Francisco]]></title>
            <link>https://medium.com/data-science/3-different-techniques-to-build-recommender-systems-for-restaurants-based-in-san-francisco-cb5c3754449e?source=rss-37344f01892b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5c3754449e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[restaurant]]></category>
            <dc:creator><![CDATA[Yue Weng Mak]]></dc:creator>
            <pubDate>Tue, 05 May 2020 17:54:42 GMT</pubDate>
            <atom:updated>2020-05-05T17:54:42.658Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hungry for food? Here are some ways to recommend a restaurant!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eBDVvqtiHWqhNDEa" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Living in a metropolitan area like San Francisco, there are so many amazing restaurants in the city. In this article, I will build a few recommender systems that will recommend similar restaurants in San Francisco.</p><p><strong>Collecting Data</strong></p><p>The data collected is from the Yelp API. Yelp provides an API that allows users to query businesses. In order for you to pull the data from Yelp, you have to set up a <a href="https://www.yelp.com/developers">developer account</a> and create an application. Yelp will generate a Client ID and the API Key for you and these credentials will be your authentication token for you to query the data.</p><p>This <a href="https://www.yelp.com/developers/documentation/v3/get_started">documentation</a> will provide you the endpoints on how to query the data. Take a look at them.</p><p>For this case, we are interested in businesses that are restaurants and location based in San Francisco. This will be the endpoint that will be relevant to my query:</p><pre><a href="https://api.yelp.com/v3/businesses/search?term=restaurants&amp;location=&#39;San">https://api.yelp.com/v3/businesses/search?term=restaurants&amp;location=&#39;San</a> Francisco&#39;</pre><p>With the URL, we are able to query the data</p><pre>import requests</pre><pre>req_business_string = &quot;<a href="https://api.yelp.com/v3/businesses/search?term=restaurants&amp;location=&#39;San">https://api.yelp.com/v3/businesses/search?term=restaurants&amp;location=&#39;San</a> Francisco&#39;&quot;</pre><pre>r = requests.get(req_business_string, <br>                 headers={&quot;content-type&quot;:&quot;application/json&quot;, <br>                          &quot;authorization&quot;: &quot;Bearer &quot; + auth_token})</pre><p>auth_token will be the API key provided to you when you create an application.</p><pre>json = r.json()<br>businesses = json[&#39;businesses&#39;]</pre><p>By running the command above, you will be able to gather the businesses from the API. Bearing in mind that the string above is filtered to restaurants in San Francisco, this is the result that will be returned. Now you have the data of the restaurants in San Francisco.</p><pre>{&#39;id&#39;: &#39;f-m7-hyFzkf0HSEeQ2s-9A&#39;,<br>  &#39;alias&#39;: &#39;fog-harbor-fish-house-san-francisco-2&#39;,<br>  &#39;name&#39;: &#39;Fog Harbor Fish House&#39;,<br>  &#39;image_url&#39;: &#39;https://s3-media1.fl.yelpcdn.com/bphoto/Lv7tIRX3Bim9bKqtWifmNg/o.jpg&#39;,<br>  &#39;is_closed&#39;: False,<br>  &#39;url&#39;: &#39;https://www.yelp.com/biz/fog-harbor-fish-house-san-francisco-2?adjust_creative=vBso-HM6oooiiw4hc86H-A&amp;utm_campaign=yelp_api_v3&amp;utm_medium=api_v3_business_search&amp;utm_source=vBso-HM6oooiiw4hc86H-A&#39;,<br>  &#39;review_count&#39;: 6050,<br>  &#39;categories&#39;: [{&#39;alias&#39;: &#39;seafood&#39;, &#39;title&#39;: &#39;Seafood&#39;},<br>   {&#39;alias&#39;: &#39;bars&#39;, &#39;title&#39;: &#39;Bars&#39;}],<br>  &#39;rating&#39;: 4.0,<br>  &#39;coordinates&#39;: {&#39;latitude&#39;: 37.809041, &#39;longitude&#39;: -122.410233},<br>  &#39;transactions&#39;: [&#39;restaurant_reservation&#39;],<br>  &#39;price&#39;: &#39;$$&#39;,<br>  &#39;location&#39;: {&#39;address1&#39;: &#39;Pier 39&#39;,<br>   &#39;address2&#39;: &#39;Ste A-202&#39;,<br>   &#39;address3&#39;: &#39;&#39;,<br>   &#39;city&#39;: &#39;San Francisco&#39;,<br>   &#39;zip_code&#39;: &#39;94133&#39;,<br>   &#39;country&#39;: &#39;US&#39;,<br>   &#39;state&#39;: &#39;CA&#39;,<br>   &#39;display_address&#39;: [&#39;Pier 39&#39;, &#39;Ste A-202&#39;, &#39;San Francisco, CA 94133&#39;]},<br>  &#39;phone&#39;: &#39;+14154212442&#39;,<br>  &#39;display_phone&#39;: &#39;(415) 421-2442&#39;,<br>  &#39;distance&#39;: 5827.740044156521}</pre><p>Here is a result of what is being returned.</p><p>Besides getting the restaurants data, we will also like to gather reviews of the particular restaurant. We can query the data by looking at the <a href="https://www.yelp.com/developers/documentation/v3/business_reviews">reviews endpoint </a>and doing a similar query.</p><p>Now we have both the restaurants’ and reviews’ data. We are going to save into a csv file so that we do not need to query the Yelp API again.</p><p><strong>Analyzing Data</strong></p><p>The next step in the process is to understand the data and analyzing the data. Based on the previous step, I stored the data in a csv file.</p><pre>import pandas as pd</pre><pre>restaurants_df = pd.read_csv(&#39;data/restaurants.csv&#39;)<br>restaurants_df.head()</pre><p>I saved the data into a data folder called restaurants.csv .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExFW2o25fJAlguEvZWYMxg.png" /></figure><p>Here is a screenshot of the restaurants table and certain columns are represented in an array or hash format. This is not an ideal format for modeling and we have to convert the data to a numerical format. Similarly, the reviews table do have the users as a hash format and we will like to parse it so that each column represents a value instead of a hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YS9XVoBaieh4AGnr" /><figcaption>Photo by <a href="https://unsplash.com/@solitsocial?utm_source=medium&amp;utm_medium=referral">Russ Widger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Clean Data</strong></p><p>In order for us to do our modeling, we need to prepare and modify the data in the right format. This includes one hot encoding and breaking the hash into single values for each column.</p><p>Looking at the restaurants table, we have categories, coordinates and location in a hash format. We have to convert them into single value columns.</p><pre>import ast<br>address = []<br>city = []<br>state = []<br>country = []<br>zipcode = []<br>for idx, row in restaurants_df.iterrows():<br>    location = ast.literal_eval(row[&#39;location&#39;])<br>    address.append(location[&#39;address1&#39;])<br>    city.append(location[&#39;city&#39;])<br>    state.append(location[&#39;state&#39;])<br>    country.append(location[&#39;country&#39;])<br>    zipcode.append(location[&#39;zip_code&#39;])<br>    <br>address_df = pd.DataFrame(address).rename(columns={0: &#39;address&#39;})<br>city_df = pd.DataFrame(city).rename(columns={0: &#39;city&#39;})<br>state_df = pd.DataFrame(state).rename(columns={0: &#39;state&#39;})<br>country_df = pd.DataFrame(country).rename(columns={0: &#39;country&#39;})<br>zip_code_df = pd.DataFrame(zipcode).rename(columns={0: &#39;zip_code&#39;})</pre><pre>lat = []<br>long = []<br>for idx, row in restaurants_df.iterrows():<br>    coord = ast.literal_eval(row[&#39;coordinates&#39;])<br>    lat.append(coord[&#39;latitude&#39;])<br>    long.append(coord[&#39;longitude&#39;])<br>    <br>lat_df = pd.DataFrame(lat).rename(columns={0: &#39;latitude&#39;})<br>long_df = pd.DataFrame(long).rename(columns={0: &#39;longitude&#39;})</pre><pre>categories_hash = {}<br>for idx, row in enumerate(restaurants_df[&#39;categories&#39;]):<br>    lst = []<br>    rows = ast.literal_eval(row)<br>    for cat in rows:<br>        lst.append(cat[&#39;title&#39;])<br>        <br>    categories_hash[idx] = &quot;, &quot;.join(lst)<br>categories_df = pd.DataFrame.from_dict(categories_hash, orient=&#39;index&#39;).rename(columns={0: &#39;cuisines&#39;})</pre><p>The code above will convert the hash into separate DataFrames with specific values.</p><p>With these dataframes created, we can perform a one hot encoding by performing a get_dummies method on the dataframe.</p><pre>cuis = categories_df[&#39;cuisines&#39;].str.split(&quot;, &quot;)<br>cuisines_dummies = pd.get_dummies(cuis.apply(pd.Series).stack()).sum(level=0)</pre><pre>transaction_df = pd.DataFrame(restaurants_df[&#39;transactions&#39;].apply(lambda x: &quot;, &quot;.join(ast.literal_eval(x)) if len(ast.literal_eval(x)) &gt; 0 else &quot;none&quot;))<br>trans = transaction_df[&#39;transactions&#39;].str.split(&quot;, &quot;)<br>transaction_dummies = pd.get_dummies(trans.apply(pd.Series).stack()).sum(level=0)</pre><p>Once they have been converted to one-hot encoding, we can concat the dataframes and drop the irrelevant columns (For modeling purpose, we need the columns to be in a numerical format so columns with strings can be dropped).</p><pre>restaurants_sim_df = pd.concat([restaurants_df, lat_df, long_df, address_df, city_df, state_df, country_df, zip_code_df, cuisines_dummies, transaction_dummies], axis=1).drop(columns=[&#39;categories&#39;, &#39;coordinates&#39;, &#39;is_closed&#39;, &#39;transactions&#39;, &#39;phone&#39;, &#39;location&#39;, &#39;_id&#39;, &#39;id&#39;, &#39;alias&#39;, &#39;name&#39;, &#39;image_url&#39;, &#39;url&#39;, &#39;review_count&#39;,&#39;display_phone&#39;, &#39;address&#39;, &#39;city&#39;, &#39;state&#39;, &#39;country&#39;,&#39;zip_code&#39;, &#39;distance&#39;, &#39;delivery&#39;, &#39;none&#39;, &#39;pickup&#39;, &#39;restaurant_reservation&#39;])</pre><p>In this snippet, I concat the original dataframe with the other dataframes that were created. I dropped the columns that are not needed. In the end result, I am left with columns with numerical values.</p><p><strong>Recommender Systems</strong></p><p>In this article, I will build out 3 different recommender systems using different techniques.</p><ol><li>Content Based Filtering using characteristic of restaurants</li><li>Content Based Filtering using Natural Language Processing (NLP)</li><li>Model Based Collaborative Filtering</li></ol><p><strong>Content Based Filtering</strong></p><ul><li>Characteristics of Restaurants</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5TZr4-sh7gJpE-Yj" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For this recommender system, we are looking at recommending restaurants that have similar characteristics, i.e. cuisines, location, price, transactions.</p><p>Using these factors, we created a matrix based on the above using cosine similarity to recommend restaurants. Cosine Similarity is a measure of similarity based on the vectors.</p><pre>from sklearn.metrics.pairwise import cosine_similarity</pre><pre>cos_sim = cosine_similarity(restaurants_sim_df, restaurants_sim_df)</pre><ul><li>Natural Language Processing (NLP)</li></ul><p>In this technique, we will be using text to recommend restaurants. The text will be from user’s reviews and similar restaurants that have similar text will be recommended.</p><p>We will be looking at the reviews table that has been generated by the reviews endpoint. It has reviews of users of different restaurants, with description of the reviews included.</p><pre>reviews_df = user_reviews_df.groupby(&#39;slug&#39;).agg({&#39;text&#39;: &#39; &#39;.join})</pre><p>First, we have to combine all texts from the same restaurants into a single row. For example, review A, B &amp; C may belong to restaurant A. We will combine these reviews together so that they represent the same reviews for a single restaurant.</p><pre>from nltk.corpus import stopwords<br>import string<br>from nltk.tokenize import sent_tokenize<br>from nltk.tokenize import word_tokenize<br>import nltk<br>nltk.download(&#39;words&#39;)<br>words = set(nltk.corpus.words.words())</pre><pre>stopwords_ = set(stopwords.words(&#39;english&#39;))<br>punctuation_ = set(string.punctuation)</pre><pre>def filter_tokens(sent):<br>    return([w for w in sent if not w in stopwords_ and not w in punctuation_])</pre><pre>def cleaned_text(string):<br>    word_list = []<br>    sent_tokens = sent_tokenize(string)<br>    tokens = [sent for sent in map(word_tokenize, sent_tokens)]<br>    <br>    tokens_lower = [[word.lower() for word in sent]<br>                 for sent in tokens]<br>    tokens_filtered = list(map(filter_tokens, tokens_lower))<br>    for tlist in tokens_filtered:<br>        for w in tlist:<br>            if w != &#39;...&#39;:<br>                word_list.append(w)<br>            <br>    return &quot; &quot;.join(word_list)</pre><pre>reviews_df[&#39;cleaned_text&#39;] = reviews_df[&#39;text&#39;].apply(lambda t: cleaned_text(t))</pre><p>In this step, we perform cleaning on the text, e.g. removing stop words and punctuation.</p><p>cleaned_text represents text that has stop words and punctuation removed.</p><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre>corpus = reviews_df[&#39;cleaned_text&#39;]</pre><pre>tf = CountVectorizer()</pre><pre>document_tf_matrix = tf.fit_transform(corpus)<br>doc_sim = cosine_similarity(document_tf_matrix, document_tf_matrix)</pre><p>A matrix is created using a CountVectorizer and cosine similarity is performed.</p><p><strong>Model Based Collaborative Filtering</strong></p><p>In this technique, we will require a user-item filtering. The last 2 techniques have been item-item filtering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tLyEUITS_OKMYFCS" /><figcaption>Photo by <a href="https://unsplash.com/@voodushevlyonniy?utm_source=medium&amp;utm_medium=referral">Valeriy Andrushko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With the reviews table, we have the restaurant slug name, user name and ratings. We can create a new matrix, having just these columns so that it will become a user-item matrix.</p><pre>ratings_df = reviews_df.merge(restaurants_name_df, left_on=&#39;slug&#39;, right_on=&#39;alias&#39;)<br>ratings_df.drop(columns=[&#39;slug&#39;, &#39;alias&#39;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*_oxnYr0BMx5UgBFA0iyiXg.png" /></figure><p>Screenshot of how it will look like</p><p>We can create a pivot table based on this by running</p><pre>ratings_crosstab = ratings_df.pivot_table(values=&#39;rating&#39;, index=&#39;user_id&#39;, columns=&#39;name&#39;, fill_value=0)</pre><p>Since most of the values will be null (not all users review all restaurants), I have filled up these values with 0.</p><p>Looking at the table, we do have many rows (restaurants) and columns (users) in this matrix. In order to reduce the number of columns, we use Singular Value Decomposition (SVD) to reduce the number of users to an x number of columns (factors). To read more about SVD, click <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition">here</a>.</p><pre>import numpy as np<br>import sklearn<br>from sklearn.decomposition import TruncatedSVD</pre><pre>SVD = TruncatedSVD(n_components=12, random_state=17)<br>resultant_matrix = SVD.fit_transform(ratings_crosstab.values.T)</pre><p>A correlation matrix can be generated</p><pre>corr_mat = np.corrcoef(resultant_matrix)</pre><p>Once the correlation matrix is generated, we are able to recommend restaurants based on the index.</p><p>If you would like to see how I generate the restaurants with the different recommender techniques, please take a look at the repository!</p><p><a href="https://github.com/yueweng/yelp_recommender_restaurants">yueweng/yelp_recommender_restaurants</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5c3754449e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/3-different-techniques-to-build-recommender-systems-for-restaurants-based-in-san-francisco-cb5c3754449e">3 Different Techniques to build Recommender Systems for Restaurants based in San Francisco</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced SQL Queries for Data Analysis]]></title>
            <link>https://levelup.gitconnected.com/advanced-sql-queries-for-data-analysis-61949a336780?source=rss-37344f01892b------2</link>
            <guid isPermaLink="false">https://medium.com/p/61949a336780</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[sql-database]]></category>
            <dc:creator><![CDATA[Yue Weng Mak]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 02:32:42 GMT</pubDate>
            <atom:updated>2020-04-22T02:32:42.350Z</atom:updated>
            <content:encoded><![CDATA[<p>More advanced SQL queries to gather and filter data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CksI-1GJZNl83usG" /><figcaption>Photo by <a href="https://unsplash.com/@nepumuk?utm_source=medium&amp;utm_medium=referral">Peter Kleinau</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SQL is a powerful language to query for data and filtering of data. In this article, we will dive into more complex queries in SQL. For the basic queries, you can head over to my article on <a href="https://levelup.gitconnected.com/common-sql-functions-for-data-scientist-dbf1359f885e"><strong>Common SQL Functions</strong></a>.</p><p>I am using the sample data we created for the article on basic queries, with some small modifications.</p><p>Here is the code:</p><pre>create table sport_types (<br>    id int,<br>    name varchar(100),<br>    location varchar(100),<br>    primary key (id)<br>);</pre><pre>create table students (<br>    id int,<br>    sport_id int,  <br>    first_name varchar(40),<br>    last_name varchar(50),<br>    gender   varchar(2),<br>    age int,<br>    grade int,<br>    primary key (id)<br>);</pre><p>I created 2 tables, sports_type and students table. sport_id in the Students table is an integer that will reference the sports_type table. We will elaborate on this more later.</p><pre>insert into sport_types values (1, &#39;Track and Field&#39;,&#39;Field&#39;);<br>insert into sport_types values (2, &#39;Soccer&#39;,&#39;Field&#39;);<br>insert into sport_types values (3, &#39;Gymnastics&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (4, &#39;Fencing&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (5, &#39;Swimming&#39;,&#39;Pool&#39;);<br>insert into sport_types values (6, &#39;Pole Vaulting&#39;,&#39;Field&#39;);<br>insert into sport_types values (7, &#39;Rugby&#39;,&#39;Field&#39;);<br>insert into sport_types values (8, &#39;Diving&#39;,&#39;Pool&#39;);<br>insert into sport_types values (9, &#39;Hockey&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (10, &#39;Frisbee&#39;,&#39;Field&#39;);<br>insert into sport_types values (11, &#39;Water Polo&#39;,&#39;Pool&#39;);<br>insert into sport_types values (12, &#39;Tennis&#39;,&#39;Court&#39;);<br>insert into sport_types values (13, &#39;Basketball&#39;,&#39;Court&#39;);<br>insert into sport_types values (14, &#39;Boxing&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (15, &#39;Volleyball&#39;,&#39;Court&#39;);</pre><pre>insert into students values (1, 9, &#39;James&#39;, &#39;Logan&#39;, &#39;M&#39;, 17, 84);<br>insert into students values (2, 5, &#39;Jack&#39;, &#39;Gilmore&#39;, &#39;M&#39;, 16, 92);<br>insert into students values (3, 5, &#39;Megan&#39;, &#39;Vansel&#39;, &#39;F&#39;, 16, 75);<br>insert into students values (4, 3, &#39;Shawn&#39;, &#39;Cattermole&#39;, &#39;M&#39;, 18, 60);<br>insert into students values (5, 15, &#39;Nicole&#39;, &#39;Lee&#39;, &#39;F&#39;, 18, 93);<br>insert into students values (6, 13, &#39;Maria&#39;, &#39;Hill&#39;, &#39;F&#39;, 17, 82);<br>insert into students values (7, 3, &#39;Wes&#39;, &#39;Owen&#39;, &#39;M&#39;, 18, 73);<br>insert into students values (8, 11, &#39;Evan&#39;, &#39;Parker&#39;, &#39;M&#39;, 17, 80);<br>insert into students values (9, 12, &#39;Archie&#39;, &#39;Dale&#39;, &#39;M&#39;, 18, 52);<br>insert into students values (10, 2, &#39;Jack&#39;, &#39;Blaine&#39;, &#39;M&#39;, 17, 77);<br>insert into students values (11, 4, &#39;Hannah&#39;, &#39;Kidd&#39;, &#39;F&#39;, 19, 91);<br>insert into students values (12, 8, &#39;Ivan&#39;, &#39;Rice&#39;, &#39;M&#39;, 16, 82);<br>insert into students values (13, 6, &#39;Vanessa&#39;, &#39;Tsu&#39;, &#39;F&#39;, 18, 71);<br>insert into students values (14, 1, &#39;Christopher&#39;, &#39;Beck&#39;, &#39;M&#39;, 18, 83);<br>insert into students values (15, 10, &#39;Clay&#39;, &#39;Powers&#39;, &#39;M&#39;, 17, 90);<br>insert into students values (16, 11, &#39;Owen&#39;, &#39;Parker&#39;, &#39;M&#39;, 19, 80);<br>insert into students values (17, 4, &#39;Jill&#39;, &#39;Powell&#39;, &#39;F&#39;, 18, 62);<br>insert into students values (18, 14, &#39;Tina&#39;, &#39;Mane&#39;, &#39;F&#39;, 19, 77);<br>insert into students values (19, 5, &#39;Michael&#39;, &#39;James&#39;, &#39;M&#39;, 19, 95);<br>insert into students values (20, 8, &#39;Jane&#39;, &#39;Bale&#39;, &#39;F&#39;, 17, 91);<br>insert into students values (21, 1, &#39;Tommy&#39;, &#39;Jones&#39;, &#39;M&#39;, 19, 86);<br>insert into students values (22, 7, &#39;Matthew&#39;, &#39;Frommers&#39;, &#39;M&#39;, 16, 57);<br>insert into students values (23, 10, &#39;Jeffery&#39;, &#39;Walsh&#39;, &#39;M&#39;, 18, 86);<br>insert into students values (24, 9, &#39;John&#39;, &#39;Lee&#39;, &#39;M&#39;, 19, 64);</pre><ul><li><strong>Alias</strong></li></ul><p>Alias is a name that you can reference in either a column of a table or the table itself. It also accounts for better readability. You can reference an alias by using as or add a space and creating a variable. Let’s look at some examples.</p><pre>SELECT age, ROUND(avg(grade), 2)<br>FROM students<br>GROUP BY age</pre><p>This query will calculate the average of the grade grouped by the age of the student. By running this command, you can see that the column name is age and round . round is not a great column name for an average and this can be confusing when the queries get more complicated. To circumvent this problem, we can set up an alias for the avg column so that it represents the value more appropriately.</p><pre>SELECT age, ROUND(avg(grade), 2) as average<br>FROM students<br>GROUP BY age</pre><p>By doing this, you set the column name to be average, replacing round with average , which represents the column more appropriately.</p><p>Alias can also help with tables name too. This will help represent the table when referencing the columns.</p><pre>SELECT s1.age, s1.grade<br>FROM students s1</pre><p>Here, you can see that we set up s1 as an alias using a space in between students and s1 . The students table has been set up as a variable s1 and we can reference the column using s1.&lt;column name&gt; -&gt; s1.age, s1.grade etc. Right now, aliasing on a table may not be very useful but when we get more complex queries, you will see that the aliasing will help in distinguishing the tables.</p><ul><li><strong>LIKE Operator</strong></li></ul><p>The LIKE Operator is commonly used in the WHERE Clause, where it will match a pattern given in a given column with wildcards in the query.</p><p>Wildcards include: % and _</p><p>% Represents any character in the column.</p><p>Here are some examples:</p><ul><li>Using % at the end</li></ul><pre>SELECT first_name, last_name, age, grade<br>FROM students<br>WHERE first_name like &#39;M%&#39;</pre><p>This query will select all rows from the students table where the first name <strong>begins</strong> with the letter ‘M’.</p><pre>| first_name   | last_name   | age     | grade   |<br>|------------- | ----------- | ------- | ------- |<br>| <strong>M</strong>egan        |  Vansel     | 16      | 75      |<br>| <strong>M</strong>aria        |  Hill       | 17      | 82      |<br>| <strong>M</strong>ichael      |  James      | 19      | 95      |<br>| <strong>M</strong>atthew      |  Frommers   | 16      | 57      |<br></pre><ul><li>Using % at the beginning</li></ul><pre>SELECT first_name, last_name, age, grade<br>FROM students<br>WHERE first_name like &#39;%an&#39;</pre><p>This query will select all rows from the students table where the first name <strong>ends </strong>with the string ‘an’.</p><pre>| first_name   | last_name   | age     | grade   |<br>|------------- | ----------- | ------- | ------- |<br>| Meg<strong>an</strong>        |  Vansel     | 16      | 75      |<br>| Ev<strong>an</strong>         |  Parker     | 17      | 80      |<br>| Iv<strong>an</strong>         |  Rice       | 16      | 82      |</pre><ul><li>Using % in the middle</li></ul><pre>SELECT first_name, last_name, age, grade<br>FROM students<br>WHERE last_name LIKE &#39;J%s&#39;</pre><p>This query will select all rows from the students table where the last name <strong>begins</strong> with ‘J’ and <strong>ends</strong> with ‘s’.</p><pre>| first_name   | last_name   | age     | grade   |<br>|------------- | ----------- | ------- | ------- |<br>| Michael      |  <strong>J</strong>ame<strong>s</strong>      | 19      | 95      |<br>| Tommy        |  <strong>J</strong>one<strong>s</strong>      | 19      | 86      |</pre><p>_ represents a single character. It is normally used with the % character in the query.</p><pre>SELECT first_name, last_name, age, grade<br>FROM students<br>WHERE first_name LIKE &#39;_e%&#39;</pre><p>This query will select all rows in the students table where the second character is an ‘e’</p><pre>| first_name   | last_name   | age     | grade   |<br>|------------- | ----------- | ------- | ------- |<br>| M<strong>e</strong>gan        |  Vansel     | 16      | 75      |<br>| W<strong>e</strong>s          |  Owen       | 18      | 73      |<br>| J<strong>e</strong>ffery      |  Walsh      | 18      | 86      |</pre><p>Some other queries:</p><pre>SELECT first_name, last_name, age, grade<br>FROM students<br>WHERE first_name LIKE &#39;__l%&#39;</pre><p>Query represents all rows in students table where the 3rd letter of the first name being an ‘l’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZV6rwupHqV2x8qCn" /><figcaption>Photo by <a href="https://unsplash.com/@cytonn_photography?utm_source=medium&amp;utm_medium=referral">Cytonn Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li><strong>JOIN Queries</strong></li></ul><p>Let’s create another table called Products. This is a table where the students will buy the product.</p><pre>create table products (<br>    id int,<br>    name varchar(100),<br>    student_id int,<br>    primary key (id)<br>);</pre><pre>insert into products values (1, &#39;LEGO&#39;, 2);<br>insert into products values (2, &#39;LEGO&#39;, 5);<br>insert into products values (3, &#39;Toy Train&#39;, 5);<br>insert into products values (4, &#39;Toy Train&#39;, 8);<br>insert into products values (5, &#39;Shirt&#39;, 10);</pre><p>A JOIN Query is used when we have to query a column from a second table. Normally there is a key from the first table that equates to a key in the second table. It can be in the form of an ID or string.</p><ul><li>INNER JOIN</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hTNisDgdIvKUB7UILt-lA.png" /></figure><p>Inner Join is joining one or more tables and selecting the rows as long as there is a match between both tables. It is like an INTERSECT.</p><pre>SELECT s.first_name, s.last_name, st.name as sport<br>FROM students s<br>INNER JOIN sport_types st<br>on s.sport_id = st.id<br>where s.age = 17</pre><p>In this select statement, we are joining the students table with the sports table on the sports_id (id in sport_types and sport_id in students) and filtering by students age (17). Notice I am using the <strong>ALIAS </strong>function, where I reference the students table as s and sport_types table as st. With this line:</p><pre>FROM students s<br>INNER JOIN sport_types st<br>on s.sport_id = st.id</pre><p>I am joining the students table with the sport_types table on the sport_id column for students and the id for sport_types. If they have the same value, SQL will return the rows.</p><p>Result:</p><pre>| first_name   | last_name   | sport        | <br>|------------- | ----------- | ------------ |<br>| Jack         |  Blaine     | Soccer       |<br>| Jane         |  Bale       | Diving       |<br>| James        |  Logan      | Hockey       |<br>| Clay         |  Powers     | Frisbee      |<br>| Evan         |  Parker     | Water Polo   |<br>| Maria        |  Hill       | Basketball   |</pre><ul><li>LEFT JOIN</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1iNsiLUtF9PhcBG2bBsGw.png" /></figure><p>LEFT JOIN selects all records from the left table and records that match the right table.</p><pre>SELECT s.first_name, s.last_name, p.name<br>From students s<br>LEFT JOIN products p<br>on p.student_id = s.id</pre><p>This query will return all the records of the left table (students) regardless of whether p.name is present. Notice that in that field p.name , it is null if there is no record of it.</p><ul><li>RIGHT JOIN</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JunwQf1N6IHjqApmkLo-AA.png" /></figure><p>RIGHT JOIN selects all records from the right table and records that match the left table.</p><ul><li>FULL OUTER JOIN</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnh8DLo15f6f2T1bTLL19g.png" /></figure><p>FULL OUTER JOIN selects all records for both the left and right tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QqP5daDSTF8VeT09" /><figcaption>Photo by <a href="https://unsplash.com/@kylejglenn?utm_source=medium&amp;utm_medium=referral">Kyle Glenn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>CASE Statement</strong></p><p>The CASE statement goes through a condition. If the condition is met, it will return the result specified and move on to the next query. It has the characteristic of an IF-ELSE statement.</p><p>Let’s look at an example.</p><p>Query: With the grades of each student available, return a letter grade.</p><ul><li>‘A’: Grade &gt; 90</li><li>‘B’: Grade between 81 and 90</li><li>‘C’: Grade between 71 and 80</li><li>‘D’: Grade between 61 and 70</li><li>‘F’: Grade 60 and under</li></ul><pre>SELECT  first_name, last_name, grade,<br>  (CASE <br>   WHEN grade &gt; 90 THEN &#39;A&#39;<br>   WHEN grade &gt; 80 AND grade &lt;= 90 THEN &#39;B&#39;<br>   WHEN grade &gt; 70 AND grade &lt;= 80 THEN &#39;C&#39;<br>   WHEN grade &gt; 60 AND grade &lt;= 70 THEN &#39;D&#39;<br>   ELSE &#39;F&#39;<br>  END) letter_grade<br>FROM students</pre><p>This query will assign a new letter_grade column and set the values to ‘A’, ‘B’, ‘C’, ‘D’ or ‘F’ based on the value in the grades column.</p><p>Run the query and see for yourself!</p><p>Look at this query:</p><pre>SELECT  (CASE <br>   WHEN grade &gt; 90 THEN &#39;A&#39;<br>   WHEN grade &gt; 80 AND grade &lt;= 90 THEN &#39;B&#39;<br>   WHEN grade &gt; 70 AND grade &lt;= 80 THEN &#39;C&#39;<br>   WHEN grade &gt; 60 AND grade &lt;= 70 THEN &#39;D&#39;<br>   ELSE &#39;F&#39;<br>  END) score,<br>  count(1)<br>FROM students<br>GROUP BY 1<br>ORDER BY 1</pre><p>What do you think this query does?</p><p>If you can figure out that this query returns the total number of letter grade for each category ordered by alphabetical order, then you are right.</p><p>Here is the explanation:</p><ul><li>We select the grade and classify them into letter grade based on the case statement</li><li>count(1) in this case is counting the case statement, since it is the first select statement in the query. Since count is an aggregate function, we need a group by method. In this case, GROUP BY 1 will be grouping the letter grades together and counting them.</li><li>ORDER BY will be sorting them based on the letter grade.</li></ul><p><strong>SUBQUERIES</strong></p><p>A Subquery is a query within a query. It is used to return data for use in the main query.</p><p>Exercise: Perform a query that returns the highest scoring student for each group. In this query, you have to return the first and last name of the student, score, and age group. If there is more than one highest score for the same age group, return all the records.</p><p>Solution:</p><pre>SELECT st.first_name, st.last_name, max_age.grade, max_age.age<br>FROM<br>(SELECT s.age age, MAX(s.grade) grade<br>From students s<br>GROUP BY s.age<br>ORDER BY s.age DESC) max_age<br>INNER JOIN students st<br>ON max_age.grade = st.grade<br>ORDER BY 4 DESC</pre><p>This query looks complicated with a query within a query. Let’s break this down:</p><p>We will first look into the subquery.</p><pre>SELECT s.age age, MAX(s.grade) grade<br>From students s<br>GROUP BY s.age<br>ORDER BY s.age DESC</pre><p>This is a normal query that we understand. Here we are selecting the age and maximum grade of the students table, setting up as an alias s, grouping them according to the age and ordering by descending order.</p><pre>(SELECT s.age age, MAX(s.grade) grade<br>From students s<br>GROUP BY s.age<br>ORDER BY s.age DESC) max_age</pre><p>This query will set up a temporary table and set up an alias called max_age.</p><pre>max_age </pre><pre>| age   | grade    |<br>|------ | -------- |<br>| 19    | 95       |<br>| 18    | 93       |<br>| 17    | 91       |<br>| 16    | 92       |</pre><p>Looking at the whole query:</p><pre>SELECT st.first_name, st.last_name, max_age.grade, max_age.age<br>FROM<br>(SELECT s.age age, MAX(s.grade) grade<br>From students s<br>GROUP BY s.age<br>ORDER BY s.age DESC) max_age<br>INNER JOIN students st<br>ON max_age.grade = st.grade<br>ORDER BY 4 DESC</pre><p>With the temporary table created, we can start querying the results based on the table. It will look like this</p><pre>SELECT st.first_name, st.last_name, max_age.grade, max_age.age<br>FROM max_age<br>INNER JOIN students st<br>ON max_age.grade = st.grade<br>ORDER BY 4 DESC</pre><p>with max_age being the temp table created. Now we can do our normal query based on what we know. The first line in the query is selecting the first_name, last_name from the table st, which is an alias for the students table and selecting the grade and age from the table max_age, which was created from the subquery. We are joining the table using inner join, with the key being the grade column. Then we order the records in descending order based on the 4th column in the select query (this happens to be the max_age.age column). You can order or group by the columns by the number, as well instead of writing the whole column out. So</p><pre>ORDER BY 1</pre><p>will order the records based on the first column in the select query, which is the st.first_name and so on.</p><p>Here is an introduction to more advanced SQL commands. Hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61949a336780" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/advanced-sql-queries-for-data-analysis-61949a336780">Advanced SQL Queries for Data Analysis</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common SQL Functions for Data Scientist]]></title>
            <link>https://levelup.gitconnected.com/common-sql-functions-for-data-scientist-dbf1359f885e?source=rss-37344f01892b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbf1359f885e</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Yue Weng Mak]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 14:34:13 GMT</pubDate>
            <atom:updated>2020-04-17T14:34:13.481Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL functions that every data scientist should know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O-Z_wOd-eHqOzexy" /><figcaption>Photo by <a href="https://unsplash.com/@tofi?utm_source=medium&amp;utm_medium=referral">Tobias Fischer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>What is SQL?</strong></h4><p>Structured Query Language (SQL) allows you to query from a database. You can perform different actions on the database including:</p><ul><li>Adding a record into the database</li><li>Updating a record into the database</li><li>Removing a record into the database</li><li>Creating tables</li></ul><p><strong>What is a Database?</strong></p><p>A database is a set of data that is stored and easily retrieved. There are different kinds of databases, such as Relational Databases and NoSQL databases. In this example, I will be using Relational Databases. Relational Database means there is a <em>structure</em> in our data. We have columns (known as fields) and rows (known as records) in our table. MySQL is an example of a Relational Database. An example of NoSQL database is MongoDB. To learn more about NoSQL databases, click <a href="https://www.mongodb.com/nosql-explained">here</a>.</p><h4><strong>Structure of a Database</strong></h4><p>There are a few components to a database:</p><ul><li>Table</li><li>Fields (Columns in a table)</li><li>Records (Rows in a table)</li></ul><p>A relational database consists of one or more tables. Each table represents an entity of the database. For example, if we have a company database, a table can represent the employees of the company or the clients of the company. Each table is a grid, with columns and rows. The columns are known as fields in the table and the rows are known as records in the table. In an employee’s table, a field can be the name of the employee, age of employee and the salary of the employee. A row is created as a record in the database. If there are 20 employees in the company, there will be 20 records in the employee’s table.</p><p>Each record will correspond to the different fields in the table. For example, if the table has fields of an employee’s name, age, and salary, it may look like this:</p><pre>Employees table<br>name    age   salary<br>Lisa    32    80000</pre><p>As you can see, the values can be a string, numeric number, etc. The values in these fields are allowed to be any of these data types:</p><ul><li>String</li><li>Int (Integer)</li><li>Float</li><li>Boolean</li></ul><p><strong><em>Let’s start with an example.</em></strong></p><p>Let’s assume that you are a sports director at school X. You have a spreadsheet of the different sports that the school offers, the number of enrollments for each sport. Your task is to put it into a SQL table for easier querying and updating. You are given a sports database.</p><ul><li>Create Table</li></ul><pre>create table sport_types (<br>    name varchar(100),<br>    location varchar(100),<br>    primary key (name)<br>);</pre><p>In this command, I have created 2 fields in the sport_types table. A name field and a location field. These fields are varchar , which is a variable-length datatype of length 100. The primary key uniquely specifies the row in the table. In this case, it is the name of the sport_type. Primary key must always be <strong>UNIQUE</strong>.</p><ul><li>Insert</li></ul><pre>insert into sport_types values (&#39;Track and Field&#39;,&#39;Field&#39;);<br>insert into sport_types values (&#39;Soccer&#39;,&#39;Field&#39;);<br>insert into sport_types values (&#39;Gymnastics&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (&#39;Fencing&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (&#39;Swimming&#39;,&#39;Pool&#39;);<br>insert into sport_types values (&#39;Pole Vaulting&#39;,&#39;Field&#39;);<br>insert into sport_types values (&#39;Rugby&#39;,&#39;Field&#39;);<br>insert into sport_types values (&#39;Diving&#39;,&#39;Pool&#39;);<br>insert into sport_types values (&#39;Hockey&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (&#39;Frisbee&#39;,&#39;Field&#39;);<br>insert into sport_types values (&#39;Water Polo&#39;,&#39;Pool&#39;);<br>insert into sport_types values (&#39;Tennis&#39;,&#39;Court&#39;);<br>insert into sport_types values (&#39;Basketball&#39;,&#39;Court&#39;);<br>insert into sport_types values (&#39;Boxing&#39;,&#39;Gymnasium&#39;);<br>insert into sport_types values (&#39;Volleyball&#39;,&#39;Court&#39;);<br>insert into sport_types values (&#39;Baseball&#39;,&#39;Field&#39;);</pre><p>I am inserting the records into the sport_types table. Notice that both fields are string. The first value will correspond to the name, and the second will be the location.</p><p>If you like to follow along, I have created another table, Students.</p><pre>create table students (<br>    id int,<br>    first_name varchar(40),<br>    last_name varchar(50),<br>    gender   varchar(2),<br>    age int,<br> grade int,<br>    sport varchar(100),<br> primary key (id)<br>);</pre><pre>insert into students values (1, &#39;James&#39;, &#39;Logan&#39;, &#39;M&#39;, 17, 84, &#39;Hockey&#39;);<br>insert into students values (2, &#39;Jack&#39;, &#39;Gilmore&#39;, &#39;M&#39;, 16, 92, &#39;Swimming&#39;);<br>insert into students values (3, &#39;Megan&#39;, &#39;Vansel&#39;, &#39;F&#39;, 16, 75, &#39;Swimming&#39;);<br>insert into students values (4, &#39;Shawn&#39;, &#39;Cattermole&#39;, &#39;M&#39;, 18, 60, &#39;Gymnastics&#39;);<br>insert into students values (5, &#39;Nicole&#39;, &#39;Lee&#39;, &#39;F&#39;, 18, 93, &#39;Volleyball&#39;);<br>insert into students values (6, &#39;Maria&#39;, &#39;Hill&#39;, &#39;F&#39;, 17, 82, &#39;Basketball&#39;);<br>insert into students values (7, &#39;Wes&#39;, &#39;Owen&#39;, &#39;M&#39;, 18, 73, &#39;Gymnastics&#39;);<br>insert into students values (8, &#39;Evan&#39;, &#39;Parker&#39;, &#39;M&#39;, 17, 80, &#39;Water Polo&#39;);<br>insert into students values (9, &#39;Archie&#39;, &#39;Dale&#39;, &#39;M&#39;, 18, 52, &#39;Tennis&#39;);<br>insert into students values (10, &#39;Jack&#39;, &#39;Blaine&#39;, &#39;M&#39;, 17, 77, &#39;Soccer&#39;);<br>insert into students values (11, &#39;Hannah&#39;, &#39;Kidd&#39;, &#39;F&#39;, 19, 91, &#39;Fencing&#39;);<br>insert into students values (12, &#39;Ivan&#39;, &#39;Rice&#39;, &#39;M&#39;, 16, 82, &#39;Diving&#39;);<br>insert into students values (13, &#39;Vanessa&#39;, &#39;Tsu&#39;, &#39;F&#39;, 18, 71, &#39;Pole Vaulting&#39;);<br>insert into students values (14, &#39;Christopher&#39;, &#39;Beck&#39;, &#39;M&#39;, 18, 83, &#39;Track and Field&#39;);<br>insert into students values (15, &#39;Clay&#39;, &#39;Powers&#39;, &#39;M&#39;, 17, 90, &#39;Frisbee&#39;);<br>insert into students values (16, &#39;Owen&#39;, &#39;Parker&#39;, &#39;M&#39;, 19, 80, &#39;Water Polo&#39;);<br>insert into students values (17, &#39;Jill&#39;, &#39;Powell&#39;, &#39;F&#39;, 18, 62, &#39;Fencing&#39;);<br>insert into students values (18, &#39;Tina&#39;, &#39;Mane&#39;, &#39;F&#39;, 19, 77, &#39;Boxing&#39;);<br>insert into students values (19, &#39;Michael&#39;, &#39;James&#39;, &#39;M&#39;, 19, 95, &#39;Swimming&#39;);<br>insert into students values (20, &#39;Jane&#39;, &#39;Bale&#39;, &#39;F&#39;, 17, 91, &#39;Diving&#39;);<br>insert into students values (21, &#39;Tommy&#39;, &#39;Jones&#39;, &#39;M&#39;, 19, 86, &#39;Track and Field&#39;);<br>insert into students values (22, &#39;Matthew&#39;, &#39;Frommers&#39;, &#39;M&#39;, 16, 57, &#39;Rugby&#39;);<br>insert into students values (23, &#39;Jeffery&#39;, &#39;Walsh&#39;, &#39;M&#39;, 18, 86, &#39;Frisbee&#39;);<br>insert into students values (24, &#39;John&#39;, &#39;Lee&#39;, &#39;M&#39;, 19, 64, &#39;Baseball&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EikHamBe7BrG1Ibj" /><figcaption>Photo by <a href="https://unsplash.com/@serenarepice?utm_source=medium&amp;utm_medium=referral">Serena Repice Lentini</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>SELECT</li></ul><p>The select function will select the fields specified. If you will want to select all rows, you can select *</p><pre>SELECT * FROM sport_types;</pre><p>This query will return all records of the table with all fields.</p><pre>SELECT name FROM sport_types;</pre><p>This query will return all records of the table with the name field. The location will NOT be returned.</p><pre>SELECT first_name, gender, sport FROM students;</pre><p>This query will return all records with the selected field, first_name, gender and sport from the table Students .</p><ul><li>WHERE</li></ul><p>When performing a SQL, sometimes we will like to filter the records returned. For example, we want to return all sports from the Pool location.</p><pre>SELECT * FROM sport_types<br>WHERE location = &#39;Pool&#39;;</pre><p>This will return all records with location = ‘Pool’</p><pre>| name        | location      |<br>|------------ | ------------- |<br>| Swimming    |  Pool         |<br>| Diving      |  Pool         |<br>| Water Polo  |  Pool         |</pre><ul><li>WHERE IN</li></ul><p>The WHERE IN clause will return records in a list or subquery</p><pre>SELECT * FROM sport_types<br>WHERE location IN (&#39;Pool&#39;, &#39;Gymnasium&#39;);</pre><p>This query will return all records with location either in ‘Pool’ or ‘Gymnasium’.</p><p>Results:</p><pre>| name        | location      |<br>|------------ | ------------- |<br>| Gymnastics  |  Gymnasium    |<br>| Fencing     |  Gymnasium    |<br>| Swimming    |  Pool         |<br>| Diving      |  Pool         |<br>| Hockey      |  Gymnasium    |<br>| Water Polo  |  Pool         |<br>| Boxing      |  Gymnasium    |</pre><ul><li>OR Clause</li></ul><p>The OR Clause will return records either with the conditions that are being met.</p><pre>SELECT * FROM sport_types<br>WHERE location = &#39;Pool&#39; <br>OR location = &#39;Gymnasium&#39;;</pre><p>This will return all records with either location = ‘Pool’ or location = ‘Gymnasium’. Notice the results is similar to the previous query (IN query).</p><ul><li>AND Clause</li></ul><p>The AND Clause will return results if all the conditions are met.</p><pre>SELECT * from sport_types<br>WHERE name = &#39;Diving&#39;<br>AND location = &#39;Pool&#39;;</pre><p>This will return all records that have name = ‘Diving’ and location = ‘Pool’.</p><p>Results:</p><pre>| name        | location      |<br>|------------ | ------------- |<br>| Diving      |  Pool         |</pre><ul><li>NOT Clause</li></ul><p>The NOT Clause will return records that negate the condition specified.</p><pre>SELECT * FROM sport_types<br>WHERE location NOT IN (&#39;Pool&#39;, &#39;Gymnasium);</pre><p>The query will return records that have locations NOT IN ‘Pool’ OR ‘Gymnasium’.</p><p>Results:</p><pre>| name             | location      |<br>|----------------  | ------------- |<br>| Track and Field  |  Field        |<br>| Soccer           |  Field        |<br>| Pole Vaulting    |  Field        |<br>| Rugby            |  Field        |<br>| Frisbee          |  Field        |<br>| Tennis           |  Court        |<br>| Basketball       |  Court        |<br>| Volleyball       |  Court        |<br>| Baseball         |  Field        |</pre><ul><li>LIMIT</li></ul><p>The limit function will limit the number of records</p><pre>SELECT * FROM sport_types<br>WHERE location = &#39;Pool&#39;<br>LIMIT 1;</pre><p>This will return the top 1 result that has a location of ‘Pool’.</p><pre>| name             | location      |<br>|----------------  | ------------- |<br>| Swimming         |  Pool         |</pre><ul><li>ORDER BY</li></ul><p>The ORDER BY clause will sort the records based on the conditions.</p><pre>SELECT * FROM sport_types<br>WHERE location = &#39;Pool&#39;<br>ORDER BY name</pre><p>This query will sort the records by name in ascending order.</p><pre>| name             | location      |<br>|----------------  | ------------- |<br>| Diving           |  Pool         |<br>| Swimming         |  Pool         |<br>| Water Polo       |  Pool         |</pre><p>You can also sort by descending order. By appending a DESC, the order will be in descending order.</p><pre>SELECT * FROM sport_types<br>WHERE location = &#39;Pool&#39;<br>ORDER BY name DESC;</pre><p>Results:</p><pre>| name             | location      |<br>|----------------  | ------------- |<br>| Water Polo       |  Pool         |<br>| Swimming         |  Pool         |<br>| Diving           |  Pool         |</pre><p>ORDER BY can also be done on numeric values. In the same way that was written, we can sort by numeric values.</p><pre>SELECT * FROM students<br>WHERE gender = &#39;M&#39;<br>ORDER BY age;</pre><p><strong>Comparison Operators</strong></p><ul><li>EQUAL(=)</li></ul><p>As you have seen from the previous queries, we have used the equal sign to denote if the field is equal to the value. We can use the equal with numeric values too.</p><ul><li>Greater than or equal to (&gt;=)</li></ul><p>The greater than or equal to signifies values greater than or equal to the value we specify.</p><pre>SELECT * FROM students<br>WHERE age &gt;= 18;</pre><p>This query returns all records with students that have the age of 18 or greater.</p><ul><li>Strictly Greater (&gt;)</li></ul><p>This query will select all records that are strictly greater than the threshold value specified.</p><pre>SELECT * FROM students<br>WHERE age &gt; 18;</pre><p>This query returns all records with students that have the age greater than 18.</p><ul><li>Less than or equal to (&lt;=)</li></ul><p>The less than or equal to signifies values less than or equal to the value we specify.</p><pre>SELECT * FROM students<br>WHERE age &lt;= 18;</pre><p>This query returns all records with students that have the age of 18 or less.</p><ul><li>Strictly Less (&lt;)</li></ul><p>This query will select all records that are strictly less than the threshold value specified.</p><pre>SELECT * FROM students<br>WHERE age &lt; 18;</pre><p>This query returns all records with students that have the age less than 18.</p><p><strong>Aggregate Functions</strong></p><ul><li>COUNT()</li></ul><p>COUNT() will count the number of records.</p><pre>SELECT COUNT(*) FROM students;</pre><p>Results:</p><pre>| count            |<br>|----------------  |<br>| 24               |</pre><ul><li>SUM()</li></ul><p>SUM() will sum up all values in the field.</p><pre>SELECT SUM(grade) FROM students;</pre><p>This query will sum up the grades of all records in the Student’s table.</p><pre>| sum              |<br>|----------------  |<br>| 1883             |</pre><ul><li>MAX()</li></ul><p>MAX() will get the maximum value.</p><pre>SELECT MAX(grade) FROM students;</pre><p>This query will select the maximum grade of all the records.</p><pre>| max              |<br>|----------------  |<br>| 95               |</pre><ul><li>MIN()</li></ul><p>MIN() will get the minimum value.</p><pre>SELECT MIN(grade) FROM students;</pre><p>This query will select the maximum grade of all the records.</p><pre>| min              |<br>|----------------  |<br>| 52               |</pre><ul><li>AVG()</li></ul><p>AVG() will get the average value.</p><pre>SELECT AVG(grade) FROM students;</pre><p>This query will select the maximum grade of all the records.</p><pre>| avg                   |<br>|---------------------- |<br>| 78.4583333333333333   |</pre><p>Looking at the values, you can see we have many decimal points. There are functions in SQL that we can perform to round the value to n number of decimal points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g-ChXxs-W-pX475Y" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>ROUND</li></ul><pre>SELECT ROUND(AVG(grade),2) FROM students;</pre><p>This will round the value to 2 decimal points.</p><ul><li>TRUNC</li></ul><pre>SELECT TRUNC(AVG(grade),2) FROM students;</pre><p>This will truncate the value to 2 decimal points.</p><ul><li>CEIL</li></ul><pre>SELECT CEIL(AVG(grade)) FROM students;</pre><p>This will round the value UP to the nearest integer.</p><ul><li>FLOOR</li></ul><pre>SELECT FLOOR(AVG(grade)) FROM students;</pre><p>This will round the value down to the nearest integer.</p><ul><li>GROUP BY</li></ul><p>The GROUP BY clause will group the records accordingly and you can perform any of these aggregate functions for more detailed querying.</p><p>Let’s assume you will like to find out what is the maximum grade, average grade and minimum grade for each age group of students.</p><pre>SELECT age, MAX(grade), ROUND(AVG(grade), 2) as avg, MIN(grade) FROM students<br>GROUP BY age<br>ORDER BY age desc</pre><p>Result:</p><pre>| age      | max      | avg     | min     |<br>|--------- | -------- |-------- |-------- |<br>| 19       | 95       | 82.17   | 64      |<br>| 18       | 93       | 72.50   | 52      |<br>| 17       | 91       | 84.00   | 77      |<br>| 16       | 92       | 76.50   | 57      |</pre><p>Hopefully, this will help with simple queries to filter and gather records! Feel free to reach out to me if you have any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbf1359f885e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/common-sql-functions-for-data-scientist-dbf1359f885e">Common SQL Functions for Data Scientist</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping using Selenium, BeautifulSoup]]></title>
            <link>https://medium.com/analytics-vidhya/web-scraping-using-selenium-beautifulsoup-a0bd87762a2c?source=rss-37344f01892b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0bd87762a2c</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python-beautifulsoup4]]></category>
            <dc:creator><![CDATA[Yue Weng Mak]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 17:31:01 GMT</pubDate>
            <atom:updated>2020-04-13T08:37:11.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2KgllBfjhytbugd" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a data scientist, gathering data is part of the job.</p><p>There are a few ways that data can be obtained. If you can get a dataset from <a href="https://www.kaggle.com/">Kaggle</a>, great! However sometimes the data is not what you want. The data may be on the site and you will like to get the information that is on the site — Introducing Web Scraping!</p><p>Web Scraping is a process of getting contents from a HTML page. The tool we are using is <strong>Selenium</strong>, that will open a browser and simulate javascript events, e.g. Click Events, Lazy Loading etc.</p><p><strong>Setup</strong></p><ol><li><strong>Install Selenium</strong></li></ol><p>pip3 install selenium</p><p>or</p><p>conda install selenium on Jupyter Notebook</p><p>2. <strong>Download Web Driver</strong></p><p>Depending on which browser you will like to use, you can download the appropriate web driver. For this tutorial, I will be using Chrome. Hence, I downloaded the <a href="https://chromedriver.chromium.org/">chrome webdriver.</a></p><p>3. <strong>Import libraries from Selenium</strong></p><pre>from selenium import webdriver<br>from selenium.webdriver.common.keys import Keys<br>from selenium.webdriver.chrome.options import Options<br>from selenium.webdriver.support.ui import WebDriverWait as wait<br>from selenium.common.exceptions import TimeoutException</pre><p>4. <strong>Setup driver to open browser</strong></p><p>In this example, I will be scraping from Vivino, a popular wine reviews site.</p><pre>url = &#39;<a href="https://www.vivino.com/explore?e=eJwdyjkKgDAURdHdvFKMQ_k6dyBWIvKNMQSMShIcdq_Y3NNcH1hmNbzbqHJ4uVnl0A-7FvpLg4MKduEpwZkkK_aJQZLbbBzlNEGswc7ZRI0r9cM3_xSI1PICdrAezQ==">https://www.vivino.com/explore?e=eJwdyjkKgDAURdHdvFKMQ_k6dyBWIvKNMQSMShIcdq_Y3NNcH1hmNbzbqHJ4uVnl0A-7FvpLg4MKduEpwZkkK_aJQZLbbBzlNEGswc7ZRI0r9cM3_xSI1PICdrAezQ==</a>&#39;</pre><pre>path = r&#39;path of where the driver is located&#39;<br>driver = webdriver.Chrome(executable_path = path)<br>driver.get(url)</pre><p>Running this will open a browser using the web driver. Now you can scrape the data by looking at the HTML on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*lxKkT4Q1FkWpLKTvvs4Eig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*k7Fat9RwbsV7U9o8VdE1PA.png" /></figure><p><strong>BeautifulSoup</strong></p><p>BeautifulSoup is a Python library that parses HTML data.</p><pre>import copy<br>from bs4 import BeautifulSoup</pre><pre>html = BeautifulSoup(driver.page_source, &#39;lxml&#39;)<br>div = html.find(&quot;div&quot;, {&quot;class&quot;: &quot;explorerPage__results--3wqLw&quot;})<br>rows = html.find_all(&quot;div&quot;, {&quot;class&quot;: &quot;explorerCard__explorerCard--3Q7_0&quot;})</pre><pre>all_rows = []</pre><pre># Let&#39;s store each row as a dictionary <br>empty_row = {<br>    &quot;title&quot;: None, &quot;location&quot;: None, &quot;price&quot;: 0.0, &quot;type&quot;: None, &quot;ratings&quot;: None, &quot;num_ratings&quot;: None, &quot;reviews&quot;: None, &quot;url&quot;: None<br>}</pre><pre>for row in rows:<br>    new_row = copy.copy(empty_row)<br>    # A list of all the entries in the row.<br>    new_row[&#39;title&#39;] = row.find(&quot;span&quot;, {&quot;class&quot;: &quot;vintageTitle__wine--U7t9G&quot;}).text<br>    location = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vintageLocation__vintageLocation--1DF0p&quot;})<br>    new_row[&#39;location&#39;] = location.findChildren()[-1].text<br>    price_button = row.find(&quot;button&quot;, {&quot;class&quot;: &quot;addToCartButton__addToCartButton--qZv9F&quot;})<br>    if price_button:<br>        new_row[&#39;price&#39;] = (float(price_button.find(&quot;span&quot;).text.replace(&quot;$&quot;, &quot;&quot;)))<br>    new_row[&#39;type&#39;] = &#39;Rosé&#39;<br>    new_row[&#39;ratings&#39;] = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vivinoRatingWide__averageValue--1zL_5&quot;}).text<br>    new_row[&#39;num_ratings&#39;] = int(row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vivinoRatingWide__basedOn--s6y0t&quot;}).text.split()[0])<br>    review_div = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;review__note--2b2DB&quot;})<br>    if review_div:<br>        new_row[&#39;reviews&#39;] = review_div.text<br>    clean_div = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;cleanWineCard__cleanWineCard--tzKxV cleanWineCard__row--CBPRR&quot;})<br>    if clean_div:<br>        new_row[&#39;url&#39;] = &#39;<a href="https://www.vivino.com&/#39;">https://www.vivino.com&#39;</a> + clean_div.find(&quot;a&quot;)[&#39;href&#39;]<br>    all_rows.append(new_row)</pre><p>Here is a sample of the subset of the results:</p><pre>[{&#39;title&#39;: &#39;Estate Pinot Noir 2016&#39;,<br>  &#39;location&#39;: &#39;Willamette Valley&#39;,<br>  &#39;price&#39;: 38.95,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.6&#39;,<br>  &#39;num_ratings&#39;: 37,<br>  &#39;reviews&#39;: None,<br>  &#39;url&#39;: &#39;https://www.vivino.com/shea-wine-cellars-estate-pinot-noir/w/12513?year=2016&amp;price_id=20572438&#39;},<br> {&#39;title&#39;: &#39;Petite Sirah 2016&#39;,<br>  &#39;location&#39;: &#39;Paso Robles&#39;,<br>  &#39;price&#39;: 39.95,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.6&#39;,<br>  &#39;num_ratings&#39;: 25,<br>  &#39;reviews&#39;: &#39;“So smooth and a little brighter than I was expecting, but nonetheless wonderful.  Not overpowering and pretty much made for food.”&#39;,<br>  &#39;url&#39;: &#39;https://www.vivino.com/aaron-petite-sirah/w/1207985?year=2016&amp;price_id=20183451&#39;},<br> {&#39;title&#39;: &#39;Las Alturas Vineyard Pinot Noir 2014&#39;,<br>  &#39;location&#39;: &#39;Santa Lucia Highlands&#39;,<br>  &#39;price&#39;: 36.99,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.5&#39;,<br>  &#39;num_ratings&#39;: 4516,<br>  &#39;reviews&#39;: &#39;“Very very good. Almost like an Orrin swift take on Pinot. Intense sweet fruit. Quite dark for a Pinot and absolutely delicious ”&#39;,<br>  &#39;url&#39;: &#39;https://www.vivino.com/belle-glos-las-alturas-vineyard-pinot-noir/w/15239?year=2014&amp;price_id=20092711&#39;},<br> {&#39;title&#39;: &#39;Clio 2017&#39;,<br>  &#39;location&#39;: &#39;Jumilla&#39;,<br>  &#39;price&#39;: 36.85,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.5&#39;,<br>  &#39;num_ratings&#39;: 569,<br>  &#39;reviews&#39;: &#39;“A savory Spanish blend of 70% Monastrell and 30% Cab that’s spectacular!\nIntoxicating nose of blueberry, forest floor, plum and menthol. Flavor packed mouth of ripe berries, cherry pie, black licorice, and juicy plum.\nSmooth tannins for a youngster with a delicate brambly finish after a 30 minute decant.\nPairs great with Manchego cheese.\nA 4.3 rating from me but this will be special for years to come.\nEs el mejor mis amigos!!!”&#39;,<br>  &#39;url&#39;: &#39;https://www.vivino.com/el-nido-clio/w/1219218?year=2017&amp;price_id=20240187&#39;},<br> {&#39;title&#39;: &#39;Cabernet Sauvignon 2018&#39;,<br>  &#39;location&#39;: &#39;Paso Robles&#39;,<br>  &#39;price&#39;: 39.89,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.5&#39;,<br>  &#39;num_ratings&#39;: 539,<br>  &#39;reviews&#39;: None,<br>  &#39;url&#39;: &#39;https://www.vivino.com/austin-hope-cabernet-sauvignon-paso-robles/w/5866389?year=2018&amp;price_id=20557366&#39;},<br> {&#39;title&#39;: &#39;Las Alturas Vineyard Pinot Noir 2018&#39;,<br>  &#39;location&#39;: &#39;Santa Lucia Highlands&#39;,<br>  &#39;price&#39;: 34.99,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.5&#39;,<br>  &#39;num_ratings&#39;: 444,<br>  &#39;reviews&#39;: None,<br>  &#39;url&#39;: &#39;https://www.vivino.com/belle-glos-las-alturas-vineyard-pinot-noir/w/15239?year=2018&amp;price_id=20711583&#39;},<br> {&#39;title&#39;: &#39;Dairyman Vineyard Pinot Noir 2018&#39;,<br>  &#39;location&#39;: &#39;Russian River Valley&#39;,<br>  &#39;price&#39;: 34.99,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.5&#39;,<br>  &#39;num_ratings&#39;: 203,<br>  &#39;reviews&#39;: None,<br>  &#39;url&#39;: &#39;https://www.vivino.com/belle-glos-dairyman-vineyard-pinot-noir/w/1561411?year=2018&amp;price_id=20468469&#39;},<br> {&#39;title&#39;: &quot;Zinfandel (Michael&#39;s Estate Vineyard) 2017&quot;,<br>  &#39;location&#39;: &#39;Paso Robles&#39;,<br>  &#39;price&#39;: 29.99,<br>  &#39;type&#39;: &#39;Rosé&#39;,<br>  &#39;ratings&#39;: &#39;4.5&#39;,<br>  &#39;num_ratings&#39;: 39,<br>  &#39;reviews&#39;: None,<br>  &#39;url&#39;: &#39;https://www.vivino.com/adelaida-cellars-zinfandel-michael-s-estate-vineyard/w/2601471?year=2017&amp;price_id=20646768&#39;}]</pre><p>Let’s try to break it down:</p><pre>import copy<br>from bs4 import BeautifulSoup</pre><ul><li>I’m importing the library copy and BeautifulSoup</li></ul><pre>html = BeautifulSoup(driver.page_source, &#39;lxml&#39;)</pre><ul><li>Here I am converting the page source into a html string</li></ul><pre>div = html.find(&quot;div&quot;, {&quot;class&quot;: &quot;explorerPage__results--3wqLw&quot;})<br>rows = html.find_all(&quot;div&quot;, {&quot;class&quot;: &quot;explorerCard__explorerCard--3Q7_0&quot;})</pre><ul><li>I am grabbing the div from the html and saving it into variables.</li></ul><pre>rows = html.find_all(&quot;div&quot;, {&quot;class&quot;: &quot;explorerCard__explorerCard--3Q7_0&quot;})</pre><p>In this snippet, I am looking for all divs that have class `explorerCard__explorerCard — 3Q7_0` and saving it into a variable rows. It will return a list of all divs with class `explorerCard__explorerCard — 3Q7_0`</p><pre>all_rows = []</pre><pre># Let&#39;s store each row as a dictionary <br>empty_row = {<br>    &quot;title&quot;: None, &quot;location&quot;: None, &quot;price&quot;: 0.0, &quot;type&quot;: None, &quot;ratings&quot;: None, &quot;num_ratings&quot;: None, &quot;reviews&quot;: None, &quot;url&quot;: None, &quot;vintage&quot;: &quot;&quot;<br>}</pre><ul><li>Initializing an empty list all_rows and an empty dictionary empty_row with quote string as keys and values as None.</li></ul><pre>for row in rows:<br>    new_row = copy.copy(empty_row)<br>    # A list of all the entries in the row.<br>    new_row[&#39;title&#39;] = row.find(&quot;span&quot;, {&quot;class&quot;: &quot;vintageTitle__wine--U7t9G&quot;}).text<br>    location = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vintageLocation__vintageLocation--1DF0p&quot;})<br>    new_row[&#39;location&#39;] = location.findChildren()[-1].text<br>    price_button = row.find(&quot;button&quot;, {&quot;class&quot;: &quot;addToCartButton__addToCartButton--qZv9F&quot;})<br>    if price_button:<br>        new_row[&#39;price&#39;] = (float(price_button.find(&quot;span&quot;).text.replace(&quot;$&quot;, &quot;&quot;)))<br>    new_row[&#39;type&#39;] = &#39;Rosé&#39;<br>    new_row[&#39;ratings&#39;] = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vivinoRatingWide__averageValue--1zL_5&quot;}).text<br>    new_row[&#39;num_ratings&#39;] = int(row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vivinoRatingWide__basedOn--s6y0t&quot;}).text.split()[0])<br>    review_div = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;review__note--2b2DB&quot;})<br>    if review_div:<br>        new_row[&#39;reviews&#39;] = review_div.text<br>    clean_div = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;cleanWineCard__cleanWineCard--tzKxV cleanWineCard__row--CBPRR&quot;})<br>    if clean_div:<br>        new_row[&#39;url&#39;] = &#39;<a href="https://www.vivino.com&/#39;">https://www.vivino.com&#39;</a> + clean_div.find(&quot;a&quot;)[&#39;href&#39;]<br>    all_rows.append(new_row)</pre><p>In this snippet, we are iterating through the rows variable (list). For each iteration, we will create a copy of the empty dictionary. For the rest of the snippet, we are looking for the respective div, grabbing the text and saving it into the key values of the dictionary. Then we append it to our main list all_rows .</p><p>Here is the code combined:</p><pre>conda install selenium<br>from selenium import webdriver<br>from selenium.webdriver.common.keys import Keys<br>from selenium.webdriver.chrome.options import Options<br>from selenium.webdriver.support.ui import WebDriverWait as wait<br>from selenium.common.exceptions import TimeoutException</pre><pre>url = &#39;<a href="https://www.vivino.com/explore?e=eJwdyjkKgDAURdHdvFKMQ_k6dyBWIvKNMQSMShIcdq_Y3NNcH1hmNbzbqHJ4uVnl0A-7FvpLg4MKduEpwZkkK_aJQZLbbBzlNEGswc7ZRI0r9cM3_xSI1PICdrAezQ==&#39;">https://www.vivino.com/explore?e=eJwdyjkKgDAURdHdvFKMQ_k6dyBWIvKNMQSMShIcdq_Y3NNcH1hmNbzbqHJ4uVnl0A-7FvpLg4MKduEpwZkkK_aJQZLbbBzlNEGswc7ZRI0r9cM3_xSI1PICdrAezQ==&#39;</a><br>path = r&#39;/Users/#{user}/Desktop/chromedriver&#39; (where the driver is located)<br>driver = webdriver.Chrome(executable_path = path)<br>driver.get(url)</pre><pre>import copy<br>from bs4 import BeautifulSoup<br>html = BeautifulSoup(driver.page_source, &#39;lxml&#39;)<br>div = html.find(&quot;div&quot;, {&quot;class&quot;: &quot;explorerPage__results--3wqLw&quot;})<br>rows = html.find_all(&quot;div&quot;, {&quot;class&quot;: &quot;explorerCard__explorerCard--3Q7_0&quot;})<br>all_rows = []<br># Let&#39;s store each row as a dictionary <br>empty_row = {<br>    &quot;title&quot;: None, &quot;location&quot;: None, &quot;price&quot;: 0.0, &quot;type&quot;: None, &quot;ratings&quot;: None, &quot;num_ratings&quot;: None, &quot;reviews&quot;: None, &quot;url&quot;: None<br>}<br>for row in rows:<br>    new_row = copy.copy(empty_row)<br>    # A list of all the entries in the row.<br>    new_row[&#39;title&#39;] = row.find(&quot;span&quot;, {&quot;class&quot;: &quot;vintageTitle__wine--U7t9G&quot;}).text<br>    location = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vintageLocation__vintageLocation--1DF0p&quot;})<br>    new_row[&#39;location&#39;] = location.findChildren()[-1].text<br>    price_button = row.find(&quot;button&quot;, {&quot;class&quot;: &quot;addToCartButton__addToCartButton--qZv9F&quot;})<br>    if price_button:<br>        new_row[&#39;price&#39;] = (float(price_button.find(&quot;span&quot;).text.replace(&quot;$&quot;, &quot;&quot;)))<br>    new_row[&#39;type&#39;] = &#39;Rosé&#39;<br>    new_row[&#39;ratings&#39;] = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vivinoRatingWide__averageValue--1zL_5&quot;}).text<br>    new_row[&#39;num_ratings&#39;] = int(row.find(&quot;div&quot;, {&quot;class&quot;: &quot;vivinoRatingWide__basedOn--s6y0t&quot;}).text.split()[0])<br>    review_div = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;review__note--2b2DB&quot;})<br>    if review_div:<br>        new_row[&#39;reviews&#39;] = review_div.text<br>    clean_div = row.find(&quot;div&quot;, {&quot;class&quot;: &quot;cleanWineCard__cleanWineCard--tzKxV cleanWineCard__row--CBPRR&quot;})<br>    if clean_div:<br>        new_row[&#39;url&#39;] = &#39;<a href="https://www.vivino.com&/#39;">https://www.vivino.com&#39;</a> + clean_div.find(&quot;a&quot;)[&#39;href&#39;]<br>    all_rows.append(new_row)</pre><p><strong>Note:</strong></p><p>Most sites are wary of bots scraping their sites for content so be careful when using Selenium. If you are not careful, your IP address will get banned.</p><p>There you go! You are able to scrape a site using Selenium!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0bd87762a2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/web-scraping-using-selenium-beautifulsoup-a0bd87762a2c">Web Scraping using Selenium, BeautifulSoup</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[Beautify Flask Web App using CSS, HTML]]></title>
            <link>https://medium.com/an-idea/beautify-flask-web-app-using-css-html-d574332f710f?source=rss-37344f01892b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d574332f710f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[template]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Yue Weng Mak]]></dc:creator>
            <pubDate>Tue, 31 Mar 2020 19:01:01 GMT</pubDate>
            <atom:updated>2020-10-07T23:58:41.818Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we add css, html to our code, check out my short post on <a href="https://medium.com/@yueweng.mak/setting-a-web-app-using-flask-python-429ac33a23d3">creating a simple app using Flask</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*dQvABiWzbE28OTPYjzElKw.png" /></figure><p>Now that we are able to create a web app using Flask, it looks dull with just some text. In this article, I will briefly explain how to add styling to the web page so that it looks like a nicer site!</p><p>I will be using the setup for the Flask tutorial as a template so that we can follow along.</p><p>Here is the source code again:</p><pre>from flask import Flask<br>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def hello_world():<br>   return &#39;Hello World&#39;</pre><pre>if __name__ == &#39;__main__&#39;:<br>   app.run()</pre><p>As a refresher, Flask needs to be installed in your machine.</p><p>def hello_word() represents the method that is being called when the index page is served. As a practice, since this is where the index page is being called, we will like to have this method defined as index() instead of hello_world() . Right now, it has only one method, but as the app grows, it will be easier to understand where the method is being called from.</p><p>Let’s change our method to index()</p><pre>from flask import Flask<br>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def index():<br>   return &#39;Hello World&#39;</pre><pre>if __name__ == &#39;__main__&#39;:<br>   app.run()</pre><p>If you look at the index method, it returns ‘Hello World’. Not very interesting, right? If you look at other sites, for example like yelp.com or airbnb.com, it looks appealing with layouts and styling integrated into the page. However by having a return in the index method, you are not able to do that.</p><h3><strong>Rendering Templates</strong></h3><p>Flask has a method, render_template . All you have to do is call that method.</p><p>from flask import Flask, render_template</p><p>Flask will look for files in the templates folder. To be explicit, you can also call this:</p><p>app = Flask(__name__, template_folder=&#39;templates&#39;)</p><p>This templates folder has to be in the same directory level as app.py</p><p>To create a folder:</p><p>In terminal: mkdir templates . Make sure you are in the project directory.</p><p>In Sublime Text: Right click on the project folder and add a new folder. Make sure the folder is in the same level as the app.py file.</p><pre>app.py<br>/templates</pre><p>In the app.py, instead of returning a string, you can call this:</p><p>return render_template(&#39;index.html&#39;) . Make sure you have a file index.html under the templates folder.</p><p>To create a file,</p><p>In terminal:</p><pre>cd templates<br>touch index.html</pre><p>In Sublime Text: Right click on the templates folder and click create new file. Save it as index.html</p><p>This will get the template under templates/index.html and return whatever content that is there.</p><p>In templates/index.html</p><pre>Hello, I am in the template folder!</pre><p>Let’s do a quick example.</p><pre>from flask import Flask, render_template<br>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def index():<br>   return render_template(&#39;index.html&#39;)</pre><pre>if __name__ == &#39;__main__&#39;:<br>   app.run()</pre><p>Restart the app and refresh the link: <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a>. You will see the changes now! Instead of having it return on app.py, It calls the template and renders the template!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J2OoMmX_0jl6ns4Z" /><figcaption>Photo by <a href="https://unsplash.com/@maxcodes?utm_source=medium&amp;utm_medium=referral">Maxwell Nelson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Adding CSS, HTML</strong></p><p><strong>Cascading Style Sheets (CSS)</strong> is for adding styles (fonts, colors etc) to a webpage. <strong>Hypertext Markup Language</strong> (<strong>HTML</strong>) is the standard <a href="https://en.wikipedia.org/wiki/Markup_language">markup language</a> for documents designed to be displayed in a <a href="https://en.wikipedia.org/wiki/Web_browser">web browser</a>.</p><p>A webpage consists of HTML elements, consisting of HTML tags.</p><p>Some common tags include:</p><ul><li>&lt;div&gt; Div Tag</li><li>&lt;span&gt; Span Tag</li><li>&lt;li&gt; List Tag</li><li>&lt;img&gt; Image Tag</li><li>and many more…</li></ul><p>Let’s create a simple HTML page. We have create a html file with index.html. Let’s proceed from there.</p><p>Suppose we have a grocery list and we want to display the list onto the page.</p><pre>&lt;h1&gt;My Grocery List&lt;/h1&gt;<br>&lt;ol&gt;<br>  &lt;li&gt;Eggs&lt;/li&gt;<br>  &lt;li&gt;Milk&lt;/li&gt;<br>  &lt;li&gt;Pasta&lt;/li&gt;<br>  &lt;li&gt;Chicken&lt;/li&gt;<br>&lt;/ol&gt;</pre><p>&lt;h1&gt; represents a h1 tag. You can have headline tags e.g. &lt;h2&gt;&lt;/h2&gt;, &lt;h3&gt;&lt;/h3&gt; etc . You will notice that each tag will be represented with a closing div tag represented by &lt;/ &gt; . This signifies that the content in between the tag is represented by that particular tag. &lt;ol&gt;&lt;/ol&gt; represents an ordered list, &lt;li&gt;&lt;/li&gt; between the &lt;ol&gt; tags signify that the list will be ordered, numbered. If you will like it to be unordered, e.g. with bullet points then use &lt;ul&gt;&lt;/ul&gt; instead. For a list of html tags, refer to <a href="https://htmldog.com/references/html/tags/">this link</a>.</p><p>Restart the app and you have created your first html page!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*2TrGZ5Oq0voWkK22pvjW4A.png" /></figure><p>Let’s add some styling to this page.</p><pre>&lt;div class=&#39;wrapper&#39; style=&#39;width:300px; margin: auto;&#39;&gt;<br>  &lt;h1 style=&#39;margin-top: 30px;&#39;&gt;My Grocery List&lt;/h1&gt;<br>  &lt;ol style=&#39;padding: 0&#39;&gt;<br>    &lt;li style=&#39;padding: 10px; font-size: 20px; color: red;&#39;&gt;Eggs&lt;/li&gt;<br>    &lt;li style=&#39;padding: 10px; font-size: 20px; color: red;&#39;&gt;Milk&lt;/li&gt;<br>    &lt;li style=&#39;padding: 10px; font-size: 20px; color: red;&#39;&gt;Pasta&lt;/li&gt;<br>    &lt;li style=&#39;padding: 10px; font-size: 20px; color: red;&#39;&gt;Chicken&lt;/li&gt;<br>  &lt;/ol&gt;<br>&lt;/div&gt;</pre><p>There are a few ways to add css. You can click on <a href="https://www.w3schools.com/css/css_howto.asp">this link</a> to see the different ways of doing so. In this example, I am using <strong>Inline CSS</strong>. This is denoted by having a <strong>style</strong> in the tag. Each style is followed by a quote and the rules for that particular div.</p><p>padding: 10px; font-size: 20px are rules. This represent the tag having a padding of 10px and font size of 20px.</p><p>For more details on how CSS work, follow <a href="https://www.w3schools.com/css/css_intro.asp">this link</a>.</p><p>There you have it, you have created a simple app with html and css!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d574332f710f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/an-idea/beautify-flask-web-app-using-css-html-d574332f710f">Beautify Flask Web App using CSS, HTML</a> was originally published in <a href="https://medium.com/an-idea">An Idea (by Ingenious Piece)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting a web app using Flask & Python]]></title>
            <link>https://medium.com/@yueweng.mak/setting-a-web-app-using-flask-python-429ac33a23d3?source=rss-37344f01892b------2</link>
            <guid isPermaLink="false">https://medium.com/p/429ac33a23d3</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yue Weng Mak]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 16:10:37 GMT</pubDate>
            <atom:updated>2020-03-31T21:11:28.073Z</atom:updated>
            <content:encoded><![CDATA[<p>As a data scientist, we worked with Jupyter Notebook and Python to run our code. I will try to explain how to use Flask to present your work as a web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LsD45UiQVTLLgI19" /><figcaption>Photo by <a href="https://unsplash.com/@bugsster?utm_source=medium&amp;utm_medium=referral">Taras Shypka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ol><li><strong>Have an Integrated Development Environment (IDE)</strong></li></ol><p>Any editor is fine, preferably with a markdown. I use Sublime Text as my IDE.</p><p><a href="https://www.sublimetext.com/">https://www.sublimetext.com/</a></p><p>2<strong>. Set up Environment</strong></p><p>Open up terminal, and run pip3 install Flask .</p><p>Once that is done, Flask is installed! Yay!</p><p><strong>3. Set up an application</strong></p><p>Let’s start with something simple. A ‘Hello World’ App.</p><p>a. Create a new project. In this case, I have added this project under Projects/flask_tutorial . Once created, open the folder in your IDE. We are going to add code in there.</p><p>b. Under the flask_tutorial folder, create a new file app.py . This is where the app will run.</p><pre>from flask import Flask<br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def hello_world():<br>   return &#39;Hello World’<br><br>if __name__ == &#39;__main__&#39;:<br>   app.run()</pre><p>Paste this into app.py . This is the underlying code to get the app up and running.</p><p>@app.route(&#39;/&#39;) signifies where the url is supposed to be. / is the index page. The method hello_world right below @app.route(&#39;/&#39;) is where it is being called when the index page is served. When a request is being sent for the index page, this method is called, in this case, printing ‘Hello World’.</p><p>c. Setting up the connection</p><p>Go to terminal and run this command:</p><pre>set FLASK_APP=app.py<br>python -m flask run</pre><p>4. When the command is executed, you will get a localhost and a port, the default will be <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a>. Enter that into your browser and you will see ‘Hello World’ printed on the screen!</p><p>5. There you have it! A simple web app!</p><p><a href="https://medium.com/@yueweng.mak/beautify-flask-web-app-using-css-html-d574332f710f">Using CSS, HTML for Flask App</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=429ac33a23d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>