<?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 Mallikarjuna G on Medium]]></title>
        <description><![CDATA[Stories by Mallikarjuna G on Medium]]></description>
        <link>https://medium.com/@data_engineer.in?source=rss-f3bfa819a2ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KEy7govkXG8uh8lszkBV0Q.jpeg</url>
            <title>Stories by Mallikarjuna G on Medium</title>
            <link>https://medium.com/@data_engineer.in?source=rss-f3bfa819a2ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:45:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@data_engineer.in/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[SFPD Crime Data Analysis — PySpark DataFrames]]></title>
            <link>https://medium.com/@data_engineer.in/sfpd-crime-data-analysis-pyspark-dataframes-391a00a47d3b?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/391a00a47d3b</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark-dataframes]]></category>
            <category><![CDATA[basics-of-apache-spark]]></category>
            <category><![CDATA[dataframes]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Thu, 24 May 2018 18:50:11 GMT</pubDate>
            <atom:updated>2018-05-24T18:50:13.503Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Readers!!</p><p>Here I am, with a fresh post on data analysis using Apache Spark Dataframes oriented towards beginners. In <a href="http://data-engineer.in/2018/05/21/auction-data-analysis-spark-dataframes-1/">previous post</a> I took eBay’s Auction Data and created a DataFrame and performed basic operations. In this post, I will take a sample of SFPD Crime data and perform basic data analysis using Apache Spark DataFrames API, wherever possible, I will include a Spark SQL notation as well along with DataFrame API notation.</p><h4>SFPD Crimes — Data Analysis</h4><p>Data used in this post can be found <a href="https://drive.google.com/open?id=1BQ0xUNeC1GTysJmWn_BudbRhX6jYRRTl">here</a>. Our dataset is a .csv file that consists of crime records from San Francisco Police Dept. Each record has an IncidentNum associated with it. Each row represents a crime incident. For each crime incident, we have the following information:</p><p>[table id=2 /]</p><p>You can run the following statements in pyspark-shell or jupyter notebook or in an IDE like PyCharm with PySpark package installed.</p><pre>#<br># Import Packages<br>#<br>from pyspark.sql import SparkSession<br>import pyspark.sql.functions as func<br><br><br>#<br># Spark Session<br>#<br>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;SFPD Crime Analysis Using DataFrames&quot;)\<br>    .getOrCreate()<br><br>#<br># ************************* SFPD dataframe creation ************************<br>#<br>sfpdHeader = (&quot;incidentnum&quot;, &quot;category&quot;, &quot;description&quot;, &quot;dayofweek&quot;, &quot;date&quot;, &quot;time&quot;, &quot;pddistrict&quot;,<br>              &quot;resolution&quot;, &quot;address&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;pdid&quot;)<br><br># Create Dataframe<br>sfpdDF = \<br>    spark.\<br>        read.\<br>        format(&quot;csv&quot;).\<br>        option(&quot;delimiter&quot;, &quot;,&quot;).\<br>        option(&quot;inferSchema&quot;, &quot;true&quot;).\<br>        load(&quot;./../data/sfpd.csv&quot;).\<br>        toDF(*sfpdHeader)<br><br>sfpdDF.persist()<br><br>sfpdDF.createOrReplaceTempView(&quot;sfpd&quot;)<br><br># <br># ********************* Explore data in the DataFrame **********************<br># 1. Top 5 Districts<br>incByDist = sfpdDF.groupBy(&quot;pddistrict&quot;).count().sort(func.desc(&quot;count&quot;))<br>incByDist.show(5)<br><br>+----------+-----+<br>|pddistrict|count|<br>+----------+-----+<br>|  SOUTHERN|73308|<br>|   MISSION|50164|<br>|  NORTHERN|46877|<br>|   CENTRAL|41914|<br>|   BAYVIEW|36111|<br>+----------+-----+<br>only showing top 5 rows<br><br><br>topByDistSQL = spark.sql(<br>    &quot;SELECT pddistrict, count(incidentnum) AS inccount FROM sfpd GROUP BY pddistrict ORDER BY inccount DESC LIMIT 5&quot;)<br>topByDistSQL.show()<br><br>+----------+--------+<br>|pddistrict|inccount|<br>+----------+--------+<br>|  SOUTHERN|   73308|<br>|   MISSION|   50164|<br>|  NORTHERN|   46877|<br>|   CENTRAL|   41914|<br>|   BAYVIEW|   36111|<br>+----------+--------+<br><br><br># 2. What are the top ten resolutions?<br>top10Res = sfpdDF.groupBy(&quot;resolution&quot;).count().sort(func.desc(&quot;count&quot;))<br>top10Res.show(10)<br><br>+--------------------+------+<br>|          resolution| count|<br>+--------------------+------+<br>|                NONE|243538|<br>|       ARREST/BOOKED| 86766|<br>|        ARREST/CITED| 22925|<br>|   PSYCHOPATHIC_CASE|  8344|<br>|             LOCATED|  6878|<br>|           UNFOUNDED|  4551|<br>|COMPLAINANT_REFUS...|  4215|<br>|     JUVENILE_BOOKED|  2381|<br>|EXCEPTIONAL_CLEAR...|  1134|<br>|      JUVENILE_CITED|  1039|<br>+--------------------+------+<br>only showing top 10 rows<br><br><br>top10ResSQL = spark.sql(<br>    &quot;SELECT resolution, count(incidentnum) AS inccount FROM sfpd GROUP BY resolution ORDER BY inccount DESC LIMIT 10&quot;)<br>top10ResSQL.show()<br><br>+--------------------+--------+<br>|          resolution|inccount|<br>+--------------------+--------+<br>|                NONE|  243538|<br>|       ARREST/BOOKED|   86766|<br>|        ARREST/CITED|   22925|<br>|   PSYCHOPATHIC_CASE|    8344|<br>|             LOCATED|    6878|<br>|           UNFOUNDED|    4551|<br>|COMPLAINANT_REFUS...|    4215|<br>|     JUVENILE_BOOKED|    2381|<br>|EXCEPTIONAL_CLEAR...|    1134|<br>|      JUVENILE_CITED|    1039|<br>+--------------------+--------+<br><br><br><br># 3. Top 3 categories<br>top3Cat = sfpdDF.groupBy(&quot;category&quot;).count().sort(func.desc(&quot;count&quot;))<br>top3Cat.show(3)<br><br>+--------------+-----+<br>|      category|count|<br>+--------------+-----+<br>| LARCENY/THEFT|96955|<br>|OTHER_OFFENSES|50611|<br>|  NON-CRIMINAL|50269|<br>+--------------+-----+<br>only showing top 3 rows<br><br><br>top3CatSQL = spark.sql(<br>    &quot;SELECT category, count(incidentnum) AS inccount FROM sfpd GROUP BY category ORDER BY inccount DESC LIMIT 3&quot;)<br>top3CatSQL.show()<br><br>+--------------+--------+<br>|      category|inccount|<br>+--------------+--------+<br>| LARCENY/THEFT|   96955|<br>|OTHER_OFFENSES|   50611|<br>|  NON-CRIMINAL|   50269|<br>+--------------+--------+<br><br><br># 4. Save the top 10 resolutions to a JSON file.<br>top10ResSQL.write.format(&quot;json&quot;).mode(&#39;overwrite&#39;).save(&quot;./../data/output/sfpd/&quot;)<br><br><br><br># *__________________________________________________________________*<br># ********************* User Defined Functions ***********************<br><br># UDF with SQL<br># 1. In PySpark, you can use registerFunction to register a Lambda function.<br><br># 2. register the function as a udf<br>spark.udf.register(&quot;getyear&quot;, lambda x: x[-2:])<br><br># 3. count of incidents by year<br>incyearSQL = spark.sql(<br>    &quot;SELECT getyear(date), count(incidentnum) AS countbyyear FROM sfpd GROUP BY getyear(date) ORDER BY countbyyear DESC&quot;)<br>incyearSQL.show()<br><br>+-------------+-----------+<br>|getyear(date)|countbyyear|<br>+-------------+-----------+<br>|           13|     152830|<br>|           14|     150185|<br>|           15|      80760|<br>+-------------+-----------+<br><br># 4. Category, resolution and address of reported incidents in 2014<br>inc2014 = spark.sql(&quot;SELECT category,address,resolution, date FROM sfpd WHERE getyear(date)=&#39;14&#39;&quot;)<br>inc2014.show()<br><br>+--------------+--------------------+-------------+--------+<br>|      category|             address|   resolution|    date|<br>+--------------+--------------------+-------------+--------+<br>|       ASSAULT|0_Block_of_UNITED...|         NONE|12/31/14|<br>|  NON-CRIMINAL|400_Block_of_POWE...|         NONE|12/31/14|<br>|       ASSAULT|700_Block_of_MONT...|         NONE|12/31/14|<br>|     VANDALISM|  FOLSOM_ST/SPEAR_ST|         NONE|12/31/14|<br>|  NON-CRIMINAL|2800_Block_of_LEA...|         NONE|12/31/14|<br>|  NON-CRIMINAL|3300_Block_of_WAS...|         NONE|12/31/14|<br>|OTHER_OFFENSES|3300_Block_of_WAS...|         NONE|12/31/14|<br>| LARCENY/THEFT|2000_Block_of_LAG...|         NONE|12/31/14|<br>| LARCENY/THEFT|   CASTRO_ST/17TH_ST|         NONE|12/31/14|<br>| LARCENY/THEFT|300_Block_of_POWE...|         NONE|12/31/14|<br>|  NON-CRIMINAL|  TAYLOR_ST/GEARY_ST|         NONE|12/31/14|<br>|  NON-CRIMINAL|1600_Block_of_THE...|         NONE|12/31/14|<br>| LARCENY/THEFT|   BUSH_ST/KEARNY_ST|         NONE|12/31/14|<br>| LARCENY/THEFT|  HARRISON_ST/7TH_ST|         NONE|12/31/14|<br>|  NON-CRIMINAL|  MARKET_ST/DRUMM_ST|         NONE|12/31/14|<br>|  NON-CRIMINAL|600_Block_of_DIVI...|         NONE|12/31/14|<br>| LARCENY/THEFT|  LARKIN_ST/HAYES_ST|         NONE|12/31/14|<br>|       ASSAULT|900_Block_of_MARK...|ARREST/BOOKED|12/31/14|<br>| VEHICLE_THEFT|DUNCAN_ST/SAN_JOS...|         NONE|12/31/14|<br>|      BURGLARY| BAKER_ST/JACKSON_ST|         NONE|12/31/14|<br>+--------------+--------------------+-------------+--------+<br>only showing top 20 rows<br><br># Can also use collect()<br><br># 5. Vandalism only in 2014 with address, resolution and category<br>van2015 = spark.sql(<br>    &quot;SELECT category,address,resolution, date FROM sfpd WHERE getyear(date)=&#39;15&#39; AND category=&#39;VANDALISM&#39;&quot;)<br>van2015.show()<br><br>+---------+--------------------+-------------+------+<br>| category|             address|   resolution|  date|<br>+---------+--------------------+-------------+------+<br>|VANDALISM|1000_Block_of_POL...|ARREST/BOOKED|7/9/15|<br>|VANDALISM|0_Block_of_VICENT...|         NONE|7/9/15|<br>|VANDALISM|500_Block_of_CAST...|         NONE|7/9/15|<br>|VANDALISM|3400_Block_of_19T...|         NONE|7/9/15|<br>|VANDALISM|700_Block_of_COLU...|         NONE|7/9/15|<br>|VANDALISM|  LINCOLN_WY/22ND_AV|         NONE|7/9/15|<br>|VANDALISM|1700_Block_of_SIL...|         NONE|7/9/15|<br>|VANDALISM|300_Block_of_POST_ST|         NONE|7/9/15|<br>|VANDALISM|GREENWICH_ST/JONE...|         NONE|7/9/15|<br>|VANDALISM|3400_Block_of_25T...|         NONE|7/9/15|<br>|VANDALISM|900_Block_of_ELLS...|         NONE|7/9/15|<br>|VANDALISM|800_Block_of_HAYE...|         NONE|7/9/15|<br>|VANDALISM|900_Block_of_GEAR...|ARREST/BOOKED|7/9/15|<br>|VANDALISM|0_Block_of_WALLER_ST|         NONE|7/9/15|<br>|VANDALISM|1700_Block_of_SUN...|         NONE|7/9/15|<br>|VANDALISM|  BUSH_ST/WEBSTER_ST|ARREST/BOOKED|7/9/15|<br>|VANDALISM|2000_Block_of_PIE...|         NONE|7/9/15|<br>|VANDALISM| QUINTARA_ST/23RD_AV|         NONE|7/9/15|<br>|VANDALISM|1900_Block_of_FIL...|         NONE|7/8/15|<br>|VANDALISM|  0_Block_of_SALA_TR|         NONE|7/8/15|<br>+---------+--------------------+-------------+------+<br>only showing top 20 rows<br><br><br>van2015.count()<br><br>3898</pre><p>Hope you got basic overview on how to create a DataFrame from a CSV file and perform basic operations. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=391a00a47d3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auction Data Analysis — PySpark DataFrames]]></title>
            <link>https://medium.com/@data_engineer.in/auction-data-analysis-pyspark-dataframes-4fa93cc4e3da?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa93cc4e3da</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Mon, 21 May 2018 03:34:15 GMT</pubDate>
            <atom:updated>2018-05-21T03:34:17.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*YxwIMnEfbkGoEBfj.png" /></figure><p>Hello Readers!!</p><p>Here I am, with a fresh post on data analysis using Apache Spark Dataframes oriented towards beginners. I took eBay’s Auction Data and created a DataFrame and performed basic operations.</p><h4>Auction Data Analysis</h4><p>Data used in this post can be found <a href="https://drive.google.com/open?id=1BQ0xUNeC1GTysJmWn_BudbRhX6jYRRTl">here</a>. Our dataset is a .csv file that consists of online auction data. Each auction has an auction id associated with it and can have multiple bids. Each row represents a bid. For each bid, we have the following information:</p><p>Column Type Description aucid String Auction ID bid Float Bid Amount bidtime Float Time of bid from start of acution bidder String The Bidder’s userid Bidrate Int Bidder’s rating openbid Float Opening Price Price Float Final Price Itemtype String Item Type dtl Int Days to Live</p><p>You can run the following statements in pyspark-shell or jupyter notebook or in an IDE like PyCharm with PySpark package installed.</p><pre># Import Packages<br>from pyspark.sql import SparkSession<br>import pyspark.sql.functions as func<br><br><br># Spark Session<br>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;Auction Data Analysis&quot;)\<br>    .getOrCreate()<br><br><br># Creating DataFrame from a CSV file with comma delimiter<br>auctiondf = \<br>    spark.\<br>        read.\<br>        format(&quot;csv&quot;).\<br>        option(&quot;delimiter&quot;, &quot;,&quot;).\<br>        option(&quot;inferSchema&quot;, &quot;true&quot;).\<br>        load(&quot;./../data/auctiondata.csv&quot;).\<br>        toDF(&quot;auctionid&quot;, &quot;bid&quot;, &quot;bidtime&quot;, &quot;bidder&quot;, &quot;bidrate&quot;, &quot;openbid&quot;, &quot;price&quot;, &quot;itemtype&quot;, &quot;dtl&quot;)<br><br><br>#1. Display data from dataframe <br><br>auctiondf.show()<br><br>+----------+-----+--------+--------------+-------+-------+-----+--------+---+<br>| auctionid|  bid| bidtime|        bidder|bidrate|openbid|price|itemtype|dtl|<br>+----------+-----+--------+--------------+-------+-------+-----+--------+---+<br>|8213034705| 95.0|2.927373|      jake7870|      0|   95.0|117.5|    xbox|  3|<br>|8213034705|115.0|2.943484| davidbresler2|      1|   95.0|117.5|    xbox|  3|<br>|8213034705|100.0|2.951285|gladimacowgirl|     58|   95.0|117.5|    xbox|  3|<br>|8213034705|117.5|2.998947|       daysrus|     10|   95.0|117.5|    xbox|  3|<br>|8213060420|  2.0|0.065266|    donnie4814|      5|    1.0|120.0|    xbox|  3|<br>|8213060420|15.25|0.123218|   myreeceyboy|     52|    1.0|120.0|    xbox|  3|<br>|8213060420|  3.0|0.186539|  parakeet2004|      5|    1.0|120.0|    xbox|  3|<br>|8213060420| 10.0| 0.18669|  parakeet2004|      5|    1.0|120.0|    xbox|  3|<br>|8213060420|24.99|0.187049|  parakeet2004|      5|    1.0|120.0|    xbox|  3|<br>|8213060420| 20.0|0.249491| bluebubbles_1|     25|    1.0|120.0|    xbox|  3|<br>|8213060420| 22.0| 0.24956| bluebubbles_1|     25|    1.0|120.0|    xbox|  3|<br>|8213060420| 24.0|0.249653| bluebubbles_1|     25|    1.0|120.0|    xbox|  3|<br>|8213060420| 26.0|0.249757| bluebubbles_1|     25|    1.0|120.0|    xbox|  3|<br>|8213060420| 80.0| 0.59059|        sa4741|      3|    1.0|120.0|    xbox|  3|<br>|8213060420| 75.0|0.657384|     jhnsn2273|     51|    1.0|120.0|    xbox|  3|<br>|8213060420| 85.0|0.657917|     jhnsn2273|     51|    1.0|120.0|    xbox|  3|<br>|8213060420| 83.0|0.816447|        sa4741|      3|    1.0|120.0|    xbox|  3|<br>|8213060420|100.0|1.005903|        sa4741|      3|    1.0|120.0|    xbox|  3|<br>|8213060420|100.0|1.012697|     jhnsn2273|     51|    1.0|120.0|    xbox|  3|<br>|8213060420|110.0|1.013056|     jhnsn2273|     51|    1.0|120.0|    xbox|  3|<br>+----------+-----+--------+--------------+-------+-------+-----+--------+---+<br>only showing top 20 rows<br><br><br>#2. Print schema of the DataFrame?<br><br>auctiondf.printSchema()<br><br>root<br> |-- auctionid: long (nullable = true)<br> |-- bid: double (nullable = true)<br> |-- bidtime: double (nullable = true)<br> |-- bidder: string (nullable = true)<br> |-- bidrate: integer (nullable = true)<br> |-- openbid: double (nullable = true)<br> |-- price: double (nullable = true)<br> |-- itemtype: string (nullable = true)<br> |-- dtl: integer (nullable = true)<br><br><br>#3. What is the total number of bids?<br><br>totbids = auctiondf.count()<br>print(&quot;Total Bids &quot; + str(totbids))<br><br>Total Bids 10654<br><br><br>#4. What is the total number of distinct items that were auctioned?<br><br>totalauctions = auctiondf.select(&quot;auctionid&quot;).distinct().count()<br>print(&quot;Total Acutions &quot; + str(totalauctions))<br><br>Total Acutions 627<br><br><br>#5. What is the total number of item types that were auctioned?<br><br>itemtypes = auctiondf.select(&quot;itemtype&quot;).distinct().count()<br>print(&quot;Total Item Types&quot; + str(itemtypes))<br><br>Total Item Types3<br><br><br>#6. What is the total number of bids per item type?<br><br>print(&quot;Total Number of Bids pers itemtype: &quot;)<br>bids_itemtype = auctiondf.groupBy(&quot;itemtype&quot;).count().show()<br><br><br>#7. What is the total number of bids per auction and item type?<br><br>print(&quot;Number of Bid per Auction and Itemtype&quot; )<br>auctiondf.groupBy(&quot;itemtype&quot;, &quot;auctionid&quot;).count().show()<br><br>Number of Bid per Auction and Itemtype<br>+--------+----------+-----+<br>|itemtype| auctionid|count|<br>+--------+----------+-----+<br>|    xbox|8215610555|   14|<br>|    xbox|8212964295|   11|<br>| cartier|1638844729|   11|<br>| cartier|1644594033|   46|<br>| cartier|1649858595|    7|<br>|    palm|3018453060|   19|<br>|    palm|3016771147|   16|<br>| cartier|1642514892|    9|<br>|    palm|3015520551|   15|<br>| cartier|1642875447|   12|<br>| cartier|1649757877|    9|<br>|    palm|3015694920|    6|<br>|    palm|3022613118|    9|<br>|    palm|3024889358|    1|<br>|    palm|3015328849|   33|<br>|    palm|3023183955|    1|<br>| cartier|1643201832|    4|<br>| cartier|1650530689|    6|<br>|    palm|3024980402|   26|<br>|    palm|3024582522|   17|<br>+--------+----------+-----+<br>only showing top 20 rows<br><br><br>#8. Across all auctioned items, what is the max number of bids?<br><br>print(&quot;Max, Min and Avg number of Bids across all Auctions&quot;)<br>auctiondf.groupBy(&quot;itemtype&quot;, &quot;auctionid&quot;).count().agg(func.min(&quot;count&quot;), func.max(&quot;count&quot;), func.avg(&quot;count&quot;)).show()<br><br>Max, Min and Avg number of Bids across all Auctions<br>+----------+----------+------------------+<br>|min(count)|max(count)|        avg(count)|<br>+----------+----------+------------------+<br>|         1|        75|16.992025518341308|<br>+----------+----------+------------------+<br><br>#9. For each auctioned Item, What is the Max, Min and Avg number of Bids? <br><br>print(&quot;For each auctioned Item, Max, Min and Avg number of Bids : &quot;)<br>auctiondf.groupBy(&quot;itemtype&quot;, &quot;auctionid&quot;).agg(func.min(&quot;bid&quot;), func.max(&quot;bid&quot;), func.avg(&quot;bid&quot;)).show()<br><br>For each auctioned Item, Max, Min and Avg number of Bids : <br>+--------+----------+--------+--------+------------------+<br>|itemtype| auctionid|min(bid)|max(bid)|          avg(bid)|<br>+--------+----------+--------+--------+------------------+<br>|    xbox|8215610555|    5.01|   35.09|22.582142857142856|<br>|    xbox|8212964295|   55.01|    86.0| 71.36454545454545|<br>| cartier|1638844729|   225.0|   320.0|284.54545454545456|<br>| cartier|1644594033|    20.0|   498.0| 156.5369565217391|<br>| cartier|1649858595|    75.0|   202.5|151.78571428571428|<br>|    palm|3018453060|   205.0|   266.0| 233.6342105263158|<br>|    palm|3016771147|     5.0|   255.0|        155.260625|<br>| cartier|1642514892|   500.0|  1025.0| 725.6111111111111|<br>|    palm|3015520551|     1.0|   232.5|103.13466666666666|<br>| cartier|1642875447|   675.0|   831.0|             754.5|<br>| cartier|1649757877|   102.5|   760.0| 348.8333333333333|<br>|    palm|3015694920|   230.0|   270.0|253.33333333333334|<br>|    palm|3022613118|   200.0|   232.5|218.61111111111111|<br>|    palm|3024889358|   240.0|   240.0|             240.0|<br>|    palm|3015328849|    12.0|   212.5| 94.59181818181817|<br>|    palm|3023183955|   250.0|   250.0|             250.0|<br>| cartier|1643201832|   999.0|  1599.0|            1274.5|<br>| cartier|1650530689|  1200.0|  3050.0|2308.3333333333335|<br>|    palm|3024980402|    0.06|   222.5|140.76346153846154|<br>|    palm|3024582522|     3.0|   255.0|161.82823529411763|<br>+--------+----------+--------+--------+------------------+<br>only showing top 20 rows<br><br>#10. Auctions with price more than 200 : <br>print(&quot;Auctions with price more than 200 : &quot; + str(auctiondf.filter(auctiondf.price&gt;200).count()))<br>Auctions with price more than 200 : 7685<br><br><br>#11. Register Temp Table and select few columns and display<br>auctiondf.createOrReplaceTempView(&quot;auctions&quot;)<br><br>xboxes = spark.sql(&quot;SELECT auctionid, itemtype,bid,price,openbid FROM auctions WHERE itemtype = &#39;xbox&#39;&quot;)<br><br>xboxes.show()<br><br>+----------+--------+-----+-----+-------+<br>| auctionid|itemtype|  bid|price|openbid|<br>+----------+--------+-----+-----+-------+<br>|8213034705|    xbox| 95.0|117.5|   95.0|<br>|8213034705|    xbox|115.0|117.5|   95.0|<br>|8213034705|    xbox|100.0|117.5|   95.0|<br>|8213034705|    xbox|117.5|117.5|   95.0|<br>|8213060420|    xbox|  2.0|120.0|    1.0|<br>|8213060420|    xbox|15.25|120.0|    1.0|<br>|8213060420|    xbox|  3.0|120.0|    1.0|<br>|8213060420|    xbox| 10.0|120.0|    1.0|<br>|8213060420|    xbox|24.99|120.0|    1.0|<br>|8213060420|    xbox| 20.0|120.0|    1.0|<br>|8213060420|    xbox| 22.0|120.0|    1.0|<br>|8213060420|    xbox| 24.0|120.0|    1.0|<br>|8213060420|    xbox| 26.0|120.0|    1.0|<br>|8213060420|    xbox| 80.0|120.0|    1.0|<br>|8213060420|    xbox| 75.0|120.0|    1.0|<br>|8213060420|    xbox| 85.0|120.0|    1.0|<br>|8213060420|    xbox| 83.0|120.0|    1.0|<br>|8213060420|    xbox|100.0|120.0|    1.0|<br>|8213060420|    xbox|100.0|120.0|    1.0|<br>|8213060420|    xbox|110.0|120.0|    1.0|<br>+----------+--------+-----+-----+-------+<br>only showing top 20 rows<br><br><br>xboxes.describe(&quot;price&quot;).show()<br><br>+-------+------------------+<br>|summary|             price|<br>+-------+------------------+<br>|  count|              2784|<br>|   mean|144.27594109195397|<br>| stddev| 72.94782944456601|<br>|    min|              31.0|<br>|    max|            501.77|<br>+-------+------------------+</pre><p>Hope you got basic overview on how to create a DataFrame from a CSV file and perform basic operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa93cc4e3da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Apache Spark — 4: Spark Vs MapReduce]]></title>
            <link>https://medium.com/@data_engineer.in/learning-apache-spark-4-spark-vs-mapreduce-53342b23bf41?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/53342b23bf41</guid>
            <category><![CDATA[learning-spark]]></category>
            <category><![CDATA[learning-apache-spark]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Thu, 10 May 2018 09:36:47 GMT</pubDate>
            <atom:updated>2018-05-10T09:36:49.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*iIZP7sCIqKn7gzG5.jpg" /></figure><p>Spark Version: Any</p><h4>Spark Vs MapReduce</h4><p>I have been thinking to write a detailed article on Spark vs MapReduce for a long time but couldn’t find time to do so. Now that I found some time, I thought of writing a post on Spark Vs MapReduce.</p><p>In my previous post, we have seen if Spark replaces Hadoop. To summarize, Spark is a strong contender to replace Hadoop MapReduce Engine. HDFS, YARN and Spark is the new standard in big data processing.</p><p>With this blog post, I intend to present the motivation behind Spark. Content will be split into three sections</p><ol><li>Overview of MapReduce Engine</li><li>Limitations of MR Engine</li><li>How Spark works differently</li></ol><h4>1. Overview of MapReduce Engine:</h4><p>I’ll not delve into the details, but, let’s look at a bird’s eye view of how Hadoop MapReduce engine works. Below picture depicts a typical Hadoop Cluster running two Map-Reduce applications. Each of these application’s Map (M) and Reduce (R) jobs are marked with black and white colors respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*JESfZ-Kg1JPS5OMr.png" /></figure><p>In brief, there is a NameNode (NN) daemon and a JobTracker (JT) daemon running on Master machines/nodes and a DataNode (DN) daemon and a TaskTracker (TT) daemons running on couple of worker/slave machines. With this background, we can summarize typical Hadoop cluster components as below -</p><ul><li><strong>NameNode (NN) and DataNodes (DN): Storage Layer</strong></li><li>NameNode and DataNodes essentially make up HDFS.</li><li>NameNode only stores the metadata of HDFS i.e., it stores the list of all files in the file system (not its data), and keeps a track of them across the cluster.</li><li>DataNodes store the actual data of files in blocks.</li><li>NameNode JVM heart beats with DataNode JVM’s every 3secs.</li><li><strong>JobTracker (JT) and TaskTracker (TT): Compute Layer</strong></li><li>JobTracker JVM is the brain of the MapReduce Engine and runs on Master Nodes.</li><li>JobTracker creates and allocates jobs to TaskTracker which runs on Slave/Worker Nodes.</li><li>TaskTrackers runs the task and reports task status to JobTracker.</li><li>Inside TaskTracker JVM, we have task slots where we run our jobs. Each slot spawns a child JVM. These slots are hardcoded to be either Map slot or Reduce slot. One cannot run a reduce job on a map slot and vice-versa.</li><li>Parallelism in MapReduce is achieved by having multiple parallel map &amp; reduce jobs running as processes in respective TaskTracker JVM slots.</li><li><strong>Job execution:</strong> In a typical MapReduce application, we chain multiple jobs of map and reduce together. It starts execution by reading a chunk of data from HDFS, run one-phase of map-reduce computation, write results back to HDFS, read those results into another map-reduce and write it back to HDFS again.</li></ul><h4>2. Limitations of MR Engine:</h4><p>We already saw in previous posts that Spark has taken direct motivation from the downsides of MapReduce computation system. Now, let’s see limitations and drawbacks of MapReduce computation engine and how Spark set out to address them:</p><p><strong>1. Parallelism via processes:</strong></p><ul><li><strong>MapReduce:</strong> MapReduce doesn’t run Map and Reduce jobs as threads. For each map/reduce job that fills a task slot, a separate child JVM is spawned. JVM processes are heavyweight and adds an overhead time for JVM Startup and Destruction</li><li><strong>Spark:</strong> On the other hand, Spark runs its jobs by spawning multiple threads running inside the same executor JVM. Threads are very light in weight when compared to JVM processes.</li></ul><p><strong>2. CPU Utilization:</strong></p><ul><li><strong>MapReduce:</strong> We saw in the first section that, task slots within TaskTracker, where Map and Reduce jobs gets executed, are not generic slots. They can run either a Map or a Reduce job but not of both types. We can categorize these slots into two types, one to run Map jobs and the other to run Reduce jobs.</li><li><strong>How does it effect a typical map reduce program?</strong></li><li>When you launch a MapReduce application, initially, the application might spend like hours and hours in just the Map phase. During this time, none of the reduce slots are going to be used. This leads to underutilization of cluster resources, so, if we notice, CPU% would not be high because all these Reduce slots are sitting empty. Facebook came up with Corona framework to address this a bit and achieved 17% performance improvements when compared to MapReduce Jobs</li><li><strong>Spark: </strong>Similar to TaskTracker JVM process in MapReduce, Spark has Executor JVMs launched on each machine. But, unlike TaskTracker, there is no hardcoding of Map and Reduce slots in Executor JVM. All task slots are generic in nature and any kind of task can run.<strong></strong></li></ul><p><strong>3. Extensive Reads and writes:</strong></p><ul><li><strong>MapReduce:</strong> In MapReduce paradigm, lot of IO occurs because of intermediate results written to HDFS and Local Node Disks and then next job reads these results. When multiple Map and Reduce jobs are chained together, then data handshake between these jobs happens via reads and writes to HDFS.</li><li><strong>Spark:</strong> Spark is designed to be an in-memory processing engine. Spark tries to keep all of the data and intermediate results in-memory. And Spark uses Directed Acyclic Graphs to chain multiple tasks which is far efficient than a typical map-reduce chain of jobs. Because of these reasons you get 10–100x faster speed than MapReduce.</li></ul><h4>3. How Spark works differently:</h4><p>Now that we have seen the disadvantages with MapReduce and how Spark addressed it, it is time to jump in and look at the internals of Spark briefly. I’ll mainly try to cover how a spark application running in a cluster looks like. Below picture depicts a typical Spark deployed in a Standalone environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*__RtGMaKlasyRW_B.png" /></figure><p>Let’s look at different components shown in the above picture:</p><ul><li><strong>Spark Master, Worker and Executor JVM’s:</strong> SparkMaster and Worker JVMs (W) (marked in orange color) are the resource managers where all worker JVM’s will register themselves with SparkMaster. Typically these processes are very small. For example: Master uses say 500MB of RAM &amp; each Worker uses say 1GB RAM. Executor JVMs (Ex) are the actual JVM processes which do data processing.</li><li><strong>Master:</strong> Master JVM’s job is to decide and schedule the launch of Executor JVM’s across the nodes. But, Mater will not launch executors, but will request Worker JVMs.</li><li><strong>Worker:</strong> Worker JVMs heartbeat with Master and launches the executors as per schedule.</li><li><strong>Executor:</strong> Executor JVM has generic slots where tasks are run as threads. Also, all the data needed to run a task is cached within Executor memory.</li><li><strong>Driver:</strong> When we start our spark application with spark-submit command, a driver JVM is launched and that driver will contact Spark Master and request launch of executors. Basically, Driver is a representative of our application and does all the communication with Spark like requested resources needed for our application.</li><li><strong>Task:</strong> Task is the smallest unit of execution which works on a partition of our data. Spark actually calls them <strong>cores</strong>, even though they are actually threads. — executor-cores setting defines number of tasks that run within the Executor. For example, if we have set — executor-cores to six, then we can run six simultaneous threads within the executor JVM.</li><li><strong>Resilience:</strong> Worker JVM’s work is only to launch Executor JVM’s whenever Master tells them to do so. If an Executor crashes, Worker will restart it. If Worker JVM crashes, Master will restart it. Master will take care of driver JVM restart as well. But then, if a driver restarts, all the Executors will have to restart.</li><li><strong>Flexible Distribution of CPU resources:</strong> By CPU resources, we mean tasks/threads running within an executor. Let’s assume that the second machine in the cluster has lot more ram and CPU resources. Can we run more threads in this second machine? Yes! You can do that by tweaking spark-env.sh file and set SPARK_WORKER_CORES to 10 in the second machine. The same setting if set to 6 in other machines, then master will launch 10 threads/tasks in that second machine and 6 in the remaining ones. But, you could still oversubscribe in general ie., executor cores setting can be 2–4 times of physical cores. SPARK_WORKER_CORES tells worker JVM as to how many cores/tasks it can give out to its underlying executor JVM’s.</li></ul><h4>Conclusion</h4><p>We’ve seen -</p><ul><li>MapReduce in a nut shell and its limitations</li><li>How Spark addressed MapReduce’s limitations.</li><li>Why is Spark orders of magnitude faster than traditional Hadoop’s map-reduce system</li><li>An overview of Spark application running in cluster</li></ul><p>That’s all there is on Spark Vs Hadoop. I hope this is useful in your learning spark journey.</p><p>If you have come this far, it means that you liked what you are reading. Why not reach little more and like and share this post.</p><p>Please comment below, I would really love to hear your thoughts and opinions on my articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53342b23bf41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark DataFrames From Strings — Scala API]]></title>
            <link>https://medium.com/@data_engineer.in/apache-spark-dataframes-from-strings-scala-api-334685f816d7?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/334685f816d7</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[implicit]]></category>
            <category><![CDATA[learning-spark]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[learning-apache-spark]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Fri, 20 Apr 2018 16:52:15 GMT</pubDate>
            <atom:updated>2018-04-20T16:52:17.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*0jghOc5GdkwytbMZ.jpg" /></figure><p><strong>Spark Version: 2.x</strong></p><p>This post is part of Apache Spark DataFrames — Scala Series.</p><h4>Apache Spark DataFrames From Strings — Scala API</h4><p>Hello Readers, In this post, I am going to show you how to create a DataFrame from a Collection of Strings using <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.package">Scala API</a>. You can copy paste the code line by line in Jupyter Notebook with <a href="https://toree.apache.org/docs/current/user/installation/">Scala-Toree Kernel</a> or to your favorite <a href="https://www.jetbrains.com/help/idea/discover-intellij-idea-for-scala.html">IDE</a> with Scala and Spark dependencies or even use Spark’s Scala shell and run these line by line.</p><p>Let us consider that I have a list or sequence of strings and the end goal is to create a dataframe from this collection of Strings.</p><h4>Step 1: Get or Create Spark Session</h4><pre>import org.apache.spark.sql.SparkSession<br><br>val spark =<br>      SparkSession.builder()<br>        .appName(&quot;DataFrames From Strings&quot;)<br>        .master(&quot;local[4]&quot;)<br>        .getOrCreate()</pre><p>local[4] means run in local mode with 4 cores.</p><h4>Step 2: Define Collection Of Strings</h4><pre>val employees = Seq(<br>      &quot;7369, SMITH, CLERK, 7902, 17-Dec-80, 800, 20, 10&quot;,<br>      &quot;7499, ALLEN, SALESMAN, 7698, 20-Feb-81, 1600, 300, 30&quot;,<br>      &quot;7521, WARD, SALESMAN, 7698, 22-Feb-81, 1250, 500, 30&quot;,<br>      &quot;7566, JONES, MANAGER, 7839, 2-Apr-81, 2975, 0, 20&quot;,<br>      &quot;7654, MARTIN, SALESMAN, 7698, 28-Sep-81, 1250, 1400, 30&quot;,<br>      &quot;7698, BLAKE, MANAGER, 7839, 1-May-81, 2850, 0, 30&quot;,<br>      &quot;7782, CLARK, MANAGER, 7839, 9-Jun-81, 2450, 0, 10&quot;,<br>      &quot;7788, SCOTT, ANALYST, 7566, 19-Apr-87, 3000, 0, 20&quot;,<br>      &quot;7839, KING, PRESIDENT, 0, 17-Nov-81, 5000, 0, 10&quot;,<br>      &quot;7844, TURNER, SALESMAN, 7698, 8-Sep-81, 1500, 0, 30&quot;,<br>      &quot;7876, ADAMS, CLERK, 7788, 23-May-87, 1100, 0, 20&quot;<br>    )</pre><h4>Step 3: Import Spark Implicits</h4><p>Importing Spark implicits is Scala specific. spark.implicits extends SQLImplicits.</p><p>By importing Spark Implicits, a lot of methods will be available for converting common Scala objects into DataFrames. Check this <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.SQLContext$implicits$">link</a> for the scala doc on this.</p><pre>import spark.implicits._</pre><h4>Step 4: Function to Cleanse Data</h4><p>If you observe above dataset, the field delimiter is “,” but there is a space as well. So, let’s define a function that takes each line and splits it by “,” (comma) and trims each field to get rid of extra space and finally returns a Row object.</p><p>A row object represents a record which is essential to create a dataFrame.</p><pre>import org.apache.spark.sql.Row<br><br>val splitAndStrip = (line: String) =&gt; {<br>      val rec = line.split(&quot;,&quot;).map(x =&gt; x.trim)<br>      Row(rec(0).toInt, rec(1), rec(2), rec(3).toInt, rec(4), rec(5).toDouble, rec(6).toDouble, rec(7).toInt)<br>    }</pre><h4>Step 5: Create DataFrame From RDD[Row]</h4><p>To create a DataFrame from an RDD of Rows, we two options:</p><ol><li>to use toDF() method</li><li>to use createDataFrame(rowRDD: RDD[Row], schema: StructType)</li></ol><p>In this post, we will see how to use toDF() method. But, it is important to note that, toDF method works if RDD is of type RDD[INT], RDD[Long], RDD[String] and RDD[T &lt;: scala.Product]. [Note: &quot;&lt;:&quot; means T must be sub type of scala.Product in which case, we can use either a Case class or a Tuple. This is because, Product is the super class of both Case class and Tuple.]</p><p>Now in this case, each Row has to be either converted to a custom Case class or to a Tuple (N-Tuple)</p><p><strong>Method 1: N Tuple:</strong></p><pre>// Method 1: N Tuple<br>val colList = List(&quot;empno&quot;, &quot;ename&quot;, &quot;job&quot;, &quot;mgr&quot;, &quot;hiredate&quot;, &quot;sal&quot;, &quot;comm&quot;, &quot;deptno&quot;)<br><br>val empDF = spark.sparkContext.parallelize(employees, 4)<br>  .map(splitAndStrip)<br>  .map{ <br>        case Row(empno: Int,ename: String,job: String,mgr: Int,hiredate: String,sal: Double,comm: Double,deptno: Int) =&gt;<br>      (empno, ename, job, mgr, hiredate, sal, comm, deptno)<br>  }.toDF(colList: _*)</pre><p><strong>Method 2: Case Class:</strong></p><pre>case class EmpFromStrings(empno: Int, ename: String, job: String, mgr: Int, hiredate: String, sal: Double, comm: Double, deptno: Int)<br><br>val employeeDF = spark.sparkContext.parallelize(employees, 4)<br>  .map(splitAndStrip)<br>  .map{<br>    case Row(empno: Int,ename: String, job: String, mgr: Int, hiredate: String, sal: Double, comm: Double, deptno: Int) =&gt;<br>      EmpFromStrings(empno, ename, job, mgr, hiredate, sal, comm, deptno)<br>  }.toDF(colList: _*)</pre><h4>Step 6: Output</h4><pre>+-----+------+---------+----+---------+------+------+------+<br>|empno| ename|      job| mgr| hiredate|   sal|  comm|deptno|<br>+-----+------+---------+----+---------+------+------+------+<br>| 7369| SMITH|    CLERK|7902|17-Dec-80| 800.0|  20.0|    10|<br>| 7499| ALLEN| SALESMAN|7698|20-Feb-81|1600.0| 300.0|    30|<br>| 7521|  WARD| SALESMAN|7698|22-Feb-81|1250.0| 500.0|    30|<br>| 7566| JONES|  MANAGER|7839| 2-Apr-81|2975.0|   0.0|    20|<br>| 7654|MARTIN| SALESMAN|7698|28-Sep-81|1250.0|1400.0|    30|<br>| 7698| BLAKE|  MANAGER|7839| 1-May-81|2850.0|   0.0|    30|<br>| 7782| CLARK|  MANAGER|7839| 9-Jun-81|2450.0|   0.0|    10|<br>| 7788| SCOTT|  ANALYST|7566|19-Apr-87|3000.0|   0.0|    20|<br>| 7839|  KING|PRESIDENT|   0|17-Nov-81|5000.0|   0.0|    10|<br>| 7844|TURNER| SALESMAN|7698| 8-Sep-81|1500.0|   0.0|    30|<br>| 7876| ADAMS|    CLERK|7788|23-May-87|1100.0|   0.0|    20|<br>+-----+------+---------+----+---------+------+------+------+</pre><h4>Step 7: Observations</h4><h4>Why are the curly brackets used and not the regular parentheses in the map?</h4><p>Ans: In general, there are many cases where we should prefer curly braces (e.g. multiline expressions, for comprehensions) etc. In this case it’s not just <em>curly braces, instead of parentheses</em>, it’s <em>curly braces with omited parentheses</em>. The curly braces here allows us to write pattern matching anonymous function inside map/filter, whereas parenthesis won’t.</p><p>That’s all reg creating Dataframes from strings. I hope this is useful in your learning spark journey.</p><p>If you have come this far, it means that you liked what you are reading. Why not reach little more and <strong>like</strong> and <strong>share</strong> this post. Please <strong>comment</strong> below, I would really love to hear your thoughts and opinions on my articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=334685f816d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark DataFrames From Tuples — Scala API]]></title>
            <link>https://medium.com/@data_engineer.in/apache-spark-dataframes-from-tuples-scala-api-39e873c60ff?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/39e873c60ff</guid>
            <category><![CDATA[basics-of-apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Fri, 20 Apr 2018 15:31:26 GMT</pubDate>
            <atom:updated>2018-04-20T15:31:28.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*ld_n-Djh9g4aHpaM.jpg" /></figure><p><strong>Spark Version: 2.x</strong></p><p>This post is part of Apache Spark DataFrames — Scala Series.</p><h4>Apache Spark DataFrames From Tuples — Scala API</h4><p>Hello Readers, In this post, I am going to show you how to create a DataFrame from a Collection of Tuples using <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.package">Scala API</a>. You can copy paste the code line by line in Jupyter Notebook with <a href="https://toree.apache.org/docs/current/user/installation/">Scala-Toree Kernel</a> or to your favorite <a href="https://www.jetbrains.com/help/idea/discover-intellij-idea-for-scala.html">IDE</a> with Scala and Spark dependencies or even use Spark’s Scala shell and run these line by line.</p><p>This is a very basic post, but there are few things to look for.</p><ol><li><em>toDF()</em> is available only when you import <em>spark.implicits._</em></li><li>Not every collection can be converted to Dataframe using toDF(). toDF works only if collection is composed of Products (i.e., case classes or tuples)</li></ol><pre>import org.apache.spark.sql.{Row, SparkSession}<br><br>object DataFrameFromTuples {<br><br>  def main(args: Array[String]) {<br>    val spark =<br>      SparkSession.builder()<br>        .appName(&quot;DataFrame-From-Tuples&quot;)<br>        .master(&quot;local[4]&quot;)<br>        .getOrCreate()<br><br>    import spark.implicits._<br><br>    // create an RDD of tuples with some data<br>    val employees = Seq(<br>      (7369, &quot;SMITH&quot;, &quot;CLERK&quot;, 7902, &quot;17-Dec-80&quot;, 800, 20, 10),<br>      (7499, &quot;ALLEN&quot;, &quot;SALESMAN&quot;, 7698, &quot;20-Feb-81&quot;, 1600, 300, 30),<br>      (7521, &quot;WARD&quot;, &quot;SALESMAN&quot;, 7698, &quot;22-Feb-81&quot;, 1250, 500, 30),<br>      (7566, &quot;JONES&quot;, &quot;MANAGER&quot;, 7839, &quot;2-Apr-81&quot;, 2975, 0, 20),<br>      (7654, &quot;MARTIN&quot;, &quot;SALESMAN&quot;, 7698, &quot;28-Sep-81&quot;, 1250, 1400, 30),<br>      (7698, &quot;BLAKE&quot;, &quot;MANAGER&quot;, 7839, &quot;1-May-81&quot;, 2850, 0, 30),<br>      (7782, &quot;CLARK&quot;, &quot;MANAGER&quot;, 7839, &quot;9-Jun-81&quot;, 2450, 0, 10),<br>      (7788, &quot;SCOTT&quot;, &quot;ANALYST&quot;, 7566, &quot;19-Apr-87&quot;, 3000, 0, 20),<br>      (7839, &quot;KING&quot;, &quot;PRESIDENT&quot;, 0, &quot;17-Nov-81&quot;, 5000, 0, 10),<br>      (7844, &quot;TURNER&quot;, &quot;SALESMAN&quot;, 7698, &quot;8-Sep-81&quot;, 1500, 0, 30),<br>      (7876, &quot;ADAMS&quot;, &quot;CLERK&quot;, 7788, &quot;23-May-87&quot;, 1100, 0, 20)<br>    )<br><br>    val empRDD = spark.sparkContext.parallelize(employees, 4)<br><br>    // convert RDD of tuples to DataFrame by supplying column names<br>    val employeeDF = empRDD.toDF(&quot;empno&quot;, &quot;ename&quot;, &quot;job&quot;, &quot;mgr&quot;, &quot;hiredate&quot;, &quot;sal&quot;, &quot;comm&quot;, &quot;deptno&quot;)<br><br>    employeeDF.printSchema()<br><br>    employeeDF.show()<br><br>  }<br><br>}</pre><p>I hope, this example is simple enough to show you how to create dataframes from tuples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39e873c60ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark DataFrames — PySpark API — Basics]]></title>
            <link>https://medium.com/@data_engineer.in/apache-spark-dataframes-pyspark-api-basics-91e69c7c3189?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/91e69c7c3189</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[learning-spark]]></category>
            <category><![CDATA[pycharm]]></category>
            <category><![CDATA[learning-apache-spark]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 13:47:38 GMT</pubDate>
            <atom:updated>2018-04-16T16:50:58.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*MbzuBUBt8fxnuf-S.jpg" /></figure><h4>Apache Spark DataFrames — PySpark API — Basics</h4><p>Hello Readers, In previous <a href="http://data-engineer.in/2018/04/15/dataframe-basics-scala/">post</a>, we have seen how to perform basic dataframe operations using <a href="https://spark.apache.org/docs/latest/api/scala/index.html">Scala API</a>. In this post, I am going to show you to similar operations on DataFrames using <a href="https://spark.apache.org/docs/latest/api/python/index.html">Python API</a>. You can copy paste the code in Jupyter Notebook with Python Kernel or to your favorite IDE with Python plugin and Spark dependencies added or even to Spark’s PySpark shell and run these one by one. I used PyCharm IDE with PySpark 2.3.0 package installed.</p><pre>&#39;&#39;&#39;<br>DataFrame Basics<br><br>@author: Mallikarjuna G<br>&#39;&#39;&#39;<br><br>if __name__ == &#39;__main__&#39;:<br>    from pyspark.sql import SparkSession<br>    from pyspark.sql import functions as F<br>    spark = SparkSession \<br>        .builder \<br>        .getOrCreate()<br><br>    sc = spark.sparkContext<br><br>    emp = [<br>        (7369, &quot;SMITH&quot;, &quot;CLERK&quot;, 7902, &quot;17-Dec-80&quot;, 800, 20, 10),<br>        (7499, &quot;ALLEN&quot;, &quot;SALESMAN&quot;, 7698, &quot;20-Feb-81&quot;, 1600, 300, 30),<br>        (7521, &quot;WARD&quot;, &quot;SALESMAN&quot;, 7698, &quot;22-Feb-81&quot;, 1250, 500, 30),<br>        (7566, &quot;JONES&quot;, &quot;MANAGER&quot;, 7839, &quot;2-Apr-81&quot;, 2975, 0, 20),<br>        (7654, &quot;MARTIN&quot;, &quot;SALESMAN&quot;, 7698, &quot;28-Sep-81&quot;, 1250, 1400, 30),<br>        (7698, &quot;BLAKE&quot;, &quot;MANAGER&quot;, 7839, &quot;1-May-81&quot;, 2850, 0, 30),<br>        (7782, &quot;CLARK&quot;, &quot;MANAGER&quot;, 7839, &quot;9-Jun-81&quot;, 2450, 0, 10),<br>        (7788, &quot;SCOTT&quot;, &quot;ANALYST&quot;, 7566, &quot;19-Apr-87&quot;, 3000, 0, 20),<br>        (7839, &quot;KING&quot;, &quot;PRESIDENT&quot;, 0, &quot;17-Nov-81&quot;, 5000, 0, 10),<br>        (7844, &quot;TURNER&quot;, &quot;SALESMAN&quot;, 7698, &quot;8-Sep-81&quot;, 1500, 0, 30),<br>        (7876, &quot;ADAMS&quot;, &quot;CLERK&quot;, 7788, &quot;23-May-87&quot;, 1100, 0, 20)<br>    ]<br><br>    headers = (&quot;empno&quot;, &quot;ename&quot;, &quot;job&quot;, &quot;mgr&quot;, &quot;hiredate&quot;, &quot;sal&quot;, &quot;comm&quot;, &quot;deptno&quot;)<br><br>    # Method 1: Creating Dataframe directly from a List of tuples<br>    empDfFromList = spark.createDataFrame(emp, headers)<br><br>    empDfFromList.show(4, truncate=False)<br><br>    # Method 2: Create an RDD from Seq of tuples with desired parallelism and then create a DataFrame<br>    empRDD = sc.parallelize(emp, 4)<br><br>    empDfFromRDD = spark.createDataFrame(empRDD, headers)<br><br>    print(&quot;*** no of partitions in empDfFrom {}&quot;.format(empDfFromList.rdd.getNumPartitions()))<br><br>    print(&quot;*** no of partitions in empDfFromList {}&quot;.format(empDfFromRDD.rdd.getNumPartitions()))<br><br>    print(&quot;*** display first two rows from the dataFrame in Array[Row] format&quot;)<br><br>    print(empDfFromRDD.head(2))<br><br>    print(&quot;*** columns just gives you the fields&quot;)<br><br>    print(empDfFromList.columns)<br><br>    print(&quot;*** It&#39;s better to use printSchema()&quot;)<br><br>    print(empDfFromList.printSchema())<br><br>    print(&quot;*** show() gives you neatly formatted data&quot;)<br><br>    print(empDfFromList.show())<br><br>    print(&quot;*** use show(n) to display n rows\n&quot;)<br><br>    empDfFromList.show(2)<br><br>    print(&quot;*** use select(n,truncate=false) to display n rows and to display column contents without truncation\n&quot;)<br><br>    empDfFromList.show(2, truncate=False)<br><br>    print(&quot;*** use select() to choose one column\n&quot;)<br><br>    empDfFromList.select(&quot;empno&quot;).show()<br><br>    print(&quot;*** use select() for multiple columns\n&quot;)<br><br>    empDfFromList.select(&quot;ename&quot;, &quot;sal&quot;).show()<br><br>    print(&quot;*** use filter() to choose rows\n&quot;)<br><br>    empDfFromList.filter(empDfFromList[&quot;job&quot;] == &quot;MANAGER&quot;).show()<br><br>    print(&quot;*** use where() to choose rows, same as filter()\n&quot;)<br><br>    empDfFromList.where(F.col(&quot;job&quot;) == &quot;MANAGER&quot;).show()<br><br>    print(&quot;*** ADVANCED: using multiple conditions in where() to choose rows\n&quot;)<br><br>    empDfFromList.where((empDfFromList.job == &quot;MANAGER&quot;) &amp; (empDfFromList.deptno.isin(10, 20)) &amp; (empDfFromList.mgr == 7839)).show()<br><br>    print(&quot;*** use as() or alias to rename columns&quot;)<br><br>    empDfFromList.select(empDfFromList.ename.alias(&quot;EmpName&quot;), empDfFromList[&quot;empno&quot;].alias(&quot;EmpNo&quot;)).show()<br><br><br>    print(&quot;*** Select list containing Column Names of type Column&quot;)<br>    empDfFromList.select(F.column(&quot;empno&quot;), F.col(&quot;ename&quot;), empDfFromList.job, empDfFromList[&quot;sal&quot;]).show(2)<br><br>    print(&quot;*** Select list with Column Names of type String&quot;)<br>    empDfFromList.select(&quot;empno&quot;, &quot;ename&quot;, &quot;mgr&quot;).show(2)<br><br>    fieldList = [&quot;ename&quot;, &quot;sal&quot;, &quot;comm&quot;, &quot;job&quot;]<br><br>    print(&quot;*** Select list of Column Names of type String&quot;)<br>    empDfFromList.select([col for col in fieldList]).show(2)<br><br>    # Define a List(Column) from List<br>    fieldListOfCol = map(lambda x : F.col(x), fieldList)<br>    print(type(fieldListOfCol))<br>    print(&quot;*** Select list with Seq of Column Names of type Column&quot;)<br>    empDfFromList.select([col for col in fieldListOfCol]).show(2)</pre><p>I hope you found this helpful in your learning-spark journey.</p><p><em>Originally published at </em><a href="http://data-engineer.in/2018/04/15/apache-spark-dataframes-pyspark-api-basics/"><em>DATA ENGINEER</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91e69c7c3189" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark DataFrames — Scala API — Basics]]></title>
            <link>https://medium.com/@data_engineer.in/apache-spark-dataframes-scala-api-basics-d0baed89c01d?source=rss-f3bfa819a2ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0baed89c01d</guid>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[learning-apache-spark]]></category>
            <category><![CDATA[basics-of-apache-spark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Mallikarjuna G]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 13:35:24 GMT</pubDate>
            <atom:updated>2018-04-20T15:32:54.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*EEV7t7YUAXgzD0AO.jpg" /></figure><h4>Apache Spark DataFrames — Scala API — Basics</h4><p>Hello Readers, In this post, I am going to show you various operations that you can perform on DataFrames using Scala API. You can copy paste the code in Jupyter Notebook with Scala-Toree Kernel or to your favorite IDE with Scala and Spark dependencies or even Spark’s Scala shell and run these one by one.</p><pre>package dataframes<br><br>import org.apache.spark.sql.SparkSession<br><br>// Define a case class<br>final case class Employee(empno: Int,<br>                          ename: String,<br>                          job: String,<br>                          mgr: Int,<br>                          hiredate: String,<br>                          sal: Double,<br>                          comm: Double,<br>                          deptno: Int<br>                         )<br><br>object Basics {<br><br>  // main method<br>  def main(arguments: Array[String]): Unit = {<br>    val spark =<br>      SparkSession.builder()<br>        .appName(&quot;DataFrame Basics&quot;)<br>        .master(&quot;local[2]&quot;)<br>        .getOrCreate()<br><br>    import spark.implicits._<br><br>    // Lets instantiate 11 employee objects and create a sequence of employees<br>    val empSeq = Seq(<br>      Employee(7369, &quot;SMITH&quot;, &quot;CLERK&quot;, 7902, &quot;17-Dec-80&quot;, 800, 20, 10),<br>      Employee(7499, &quot;ALLEN&quot;, &quot;SALESMAN&quot;, 7698, &quot;20-Feb-81&quot;, 1600, 300, 30),<br>      Employee(7521, &quot;WARD&quot;, &quot;SALESMAN&quot;, 7698, &quot;22-Feb-81&quot;, 1250, 500, 30),<br>      Employee(7566, &quot;JONES&quot;, &quot;MANAGER&quot;, 7839, &quot;2-Apr-81&quot;, 2975, 0, 20),<br>      Employee(7654, &quot;MARTIN&quot;, &quot;SALESMAN&quot;, 7698, &quot;28-Sep-81&quot;, 1250, 1400, 30),<br>      Employee(7698, &quot;BLAKE&quot;, &quot;MANAGER&quot;, 7839, &quot;1-May-81&quot;, 2850, 0, 30),<br>      Employee(7782, &quot;CLARK&quot;, &quot;MANAGER&quot;, 7839, &quot;9-Jun-81&quot;, 2450, 0, 10),<br>      Employee(7788, &quot;SCOTT&quot;, &quot;ANALYST&quot;, 7566, &quot;19-Apr-87&quot;, 3000, 0, 20),<br>      Employee(7839, &quot;KING&quot;, &quot;PRESIDENT&quot;, 0, &quot;17-Nov-81&quot;, 5000, 0, 10),<br>      Employee(7844, &quot;TURNER&quot;, &quot;SALESMAN&quot;, 7698, &quot;8-Sep-81&quot;, 1500, 0, 30),<br>      Employee(7876, &quot;ADAMS&quot;, &quot;CLERK&quot;, 7788, &quot;23-May-87&quot;, 1100, 0, 20)<br>    )<br><br>    // Method 1: Creating Dataframe directly from a Seq of Objects<br>    val empDfFromSeq = spark.createDataFrame(empSeq)<br><br>    // Method 2: Create an RDD from Seq of Objects with desired parallelism and then create a DataFrame<br>    val empRDD = spark.sparkContext.parallelize(empSeq,4)<br><br>    val empDfFromRDD = spark.createDataFrame(empRDD)<br><br>    println(s&quot;*** no of partitions in empDfFromSeq ${empDfFromSeq.rdd.getNumPartitions}&quot;)<br><br>    println(s&quot;*** no of partitions in empDfFromSeq ${empDfFromRDD.rdd.getNumPartitions}&quot;)<br><br>    println(&quot;*** display first two rows from the dataFrame in Array[Row] format&quot;)<br><br>    empDfFromRDD head 2 foreach println<br><br>    println(&quot;*** toString() just gives you the schema&quot;)<br><br>    println(empDfFromSeq.toString())<br><br>    println(&quot;*** columns just gives you the fields&quot;)<br><br>    println(empDfFromSeq.columns.foreach(println))<br><br>    println(&quot;*** It&#39;s better to use printSchema()&quot;)<br><br>    empDfFromSeq.printSchema()<br><br>    println(&quot;*** show() gives you neatly formatted data&quot;)<br><br>    empDfFromSeq.show()<br><br>    println(&quot;*** use show(n) to display n rows&quot;)<br><br>    empDfFromSeq.show(2)<br><br>    println(&quot;*** use select(n,truncate=false) to display n rows and to display column contents without truncation&quot;)<br><br>    empDfFromSeq.show(2, truncate = false)<br><br>    println(&quot;*** use select() to choose one column&quot;)<br><br>    empDfFromSeq.select(&quot;empno&quot;).show()<br><br>    println(&quot;*** use select() for multiple columns&quot;)<br><br>    empDfFromSeq.select(&quot;ename&quot;, &quot;sal&quot;).show()<br><br>    println(&quot;*** use filter() to choose rows&quot;)<br><br>    empDfFromSeq.filter($&quot;job&quot;.equalTo(&quot;MANAGER&quot;)).show()<br><br>    println(&quot;*** use where() to choose rows, same as filter()&quot;)<br><br>    empDfFromSeq.where($&quot;job&quot;.equalTo(&quot;MANAGER&quot;)).show()<br><br>    println(&quot;*** ADVANCED: using multiple conditions in where() to choose rows&quot;)<br><br>    empDfFromSeq<br>      .where($&quot;job&quot;.equalTo(&quot;MANAGER&quot;)<br>        .and($&quot;deptno&quot;.isin(10,20))<br>        .and($&quot;mgr&quot;.equalTo(7839))).show()<br><br>    println(&quot;*** use as() or alias to rename columns&quot;)<br><br>    empDfFromSeq.select($&quot;ename&quot;.as(&quot;EmpName&quot;), $&quot;empno&quot;.alias(&quot;EmpNo&quot;)).show()<br><br>    // Ways to select columns<br>    import org.apache.spark.sql.functions.col<br>    import org.apache.spark.sql.functions.column<br><br>    println(&quot;*** Select list containing Column Names of type Column&quot;)<br>    empDfFromSeq.select(column(&quot;empno&quot;), col(&quot;ename&quot;), empDfFromSeq.col(&quot;job&quot;), $&quot;sal&quot;).show(2)<br><br>    println(&quot;*** Select list with Column Names of type String&quot;)<br>    empDfFromSeq.select(&quot;empno&quot;, &quot;ename&quot;, &quot;mgr&quot;).show(2)<br><br>    // Ways to Select Seq of Columns<br>    val fieldList = List(&quot;ename&quot;, &quot;sal&quot;, &quot;comm&quot;, &quot;job&quot;)<br><br>    println(&quot;*** Select list with Seq of Column Names of type String&quot;)<br>    empDfFromSeq.select(fieldList.head, fieldList.tail :_*).show(2)<br><br>    // Define a List[Column] from List[String]<br>    val fieldListOfCol = fieldList.map(col) // same as fieldList.map(x =&gt; col(x))<br><br>    println(&quot;*** Select list with Seq of Column Names of type Column&quot;)<br>    empDfFromSeq.select(fieldListOfCol :_*).show(2)<br><br>  }<br><br>}</pre><p>Hope, you find it useful in your learning-spark journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0baed89c01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>