Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added sys path to guarantee imports | Added SparkConf to all files#7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
jleetutorial merged 2 commits intomasterfrompedro-changes-path
Feb 4, 2018
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletionsadvanced/accumulator/StackOverFlowSurvey.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

def filterResponseFromCanada(response, total, missingSalaryMidPoint):
splits = Utils.COMMA_DELIMITER.split(response)
total.add(1)
if not splits[14]:
missingSalaryMidPoint.add(1)
return splits[2] == "Canada"

if __name__ == "__main__":
sc = SparkContext("local", "StackOverFlowSurvey")
sc.setLogLevel("ERROR")

conf = SparkConf().setAppName('StackOverFlowSurvey').setMaster("local[*]")
sc = SparkContext(conf = conf)
total = sc.accumulator(0)
missingSalaryMidPoint = sc.accumulator(0)

responseRDD = sc.textFile("in/2016-stack-overflow-survey-responses.csv")

responseFromCanada = responseRDD.filter(lambda response: \
filterResponseFromCanada(response, total, missingSalaryMidPoint))
def filterResponseFromCanada(response):
splits = Utils.COMMA_DELIMITER.split(response)
total.add(1)
if not splits[14]:
missingSalaryMidPoint.add(1)
return splits[2] == "Canada"

responseFromCanada = responseRDD.filter(filterResponseFromCanada)
print("Count of responses from Canada: {}".format(responseFromCanada.count()))
print("Total count of responses: {}".format(total.value))
print("Count of responses missing salary middle point: {}".format(missingSalaryMidPoint.value))
print("Count of responses missing salary middle point: {}" \
.format(missingSalaryMidPoint.value))
27 changes: 13 additions & 14 deletionsadvanced/accumulator/StackOverFlowSurveyFollowUp.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

def filterResponseFromCanada(response, total, missingSalaryMidPoint, processedBytes):
processedBytes.add(len(response.encode('utf-8')))
splits = Utils.COMMA_DELIMITER.split(response)
total.add(1)
if not splits[14]:
missingSalaryMidPoint.add(1)
return splits[2] == "Canada"

if __name__ == "__main__":
sc =SparkContext("local", "StackOverFlowSurvey")
sc.setLogLevel("ERROR")
conf =SparkConf().setAppName('StackOverFlowSurvey').setMaster("local[*]")
sc = SparkContext(conf = conf)

total = sc.accumulator(0)
missingSalaryMidPoint = sc.accumulator(0)
processedBytes = sc.accumulator(0)

responseRDD = sc.textFile("in/2016-stack-overflow-survey-responses.csv")

responseFromCanada = responseRDD.filter(lambda response: \
filterResponseFromCanada(response, total, missingSalaryMidPoint, processedBytes))
def filterResponseFromCanada(response):
processedBytes.add(len(response.encode('utf-8')))
splits = Utils.COMMA_DELIMITER.split(response)
total.add(1)
if not splits[14]:
missingSalaryMidPoint.add(1)
return splits[2] == "Canada"
responseFromCanada = responseRDD.filter(filterResponseFromCanada)

print("Count of responses from Canada: {}".format(responseFromCanada.count()))
print("Number of bytes processed: {}".format(processedBytes.value))
Expand Down
18 changes: 10 additions & 8 deletionsadvanced/broadcast/UkMakerSpaces.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

def getPostPrefix(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
postcode = splits[4]
return None if not postcode else postcode.split(" ")[0]

def loadPostCodeMap():
lines = open("in/uk-postcode.csv", "r").read().split("\n")
splitsForLines = [Utils.COMMA_DELIMITER.split(line) for line in lines if line != ""]
return {splits[0]: splits[7] for splits in splitsForLines}

def getPostPrefix(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
postcode = splits[4]
return None if not postcode else postcode.split(" ")[0]

if __name__ == "__main__":
sc =SparkContext("local", "UkMakerSpaces")
sc.setLogLevel("ERROR")
conf =SparkConf().setAppName('UkMakerSpaces').setMaster("local[*]")
sc = SparkContext(conf = conf)

postCodeMap = sc.broadcast(loadPostCodeMap())

Expand Down
22 changes: 12 additions & 10 deletionsadvanced/broadcast/UkMakerSpacesWithoutBroadcast.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

def getPostPrefixes(line: str):
postcode = Utils.COMMA_DELIMITER.split(line)[4]
cleanedPostCode = postcode.replace("\\s+", "")
return [cleanedPostCode[0:i] for i in range(0,len(cleanedPostCode)+1)]

def loadPostCodeMap():
lines = open("in/uk-postcode.csv", "r").read().split("\n")
splitsForLines = [Utils.COMMA_DELIMITER.split(line) for line in lines if line != ""]
return {splits[0]: splits[7] for splits in splitsForLines}

def getPostPrefix(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
postcode = splits[4]
return None if not postcode else postcode.split(" ")[0]

if __name__ == "__main__":
sc =SparkContext("local", "UkMakerSpaces")
sc.setLogLevel("ERROR")
conf =SparkConf().setAppName('UkMakerSpaces').setMaster("local[*]")
sc = SparkContext(conf = conf)
postCodeMap = loadPostCodeMap()
makerSpaceRdd = sc.textFile("in/uk-makerspaces-identifiable-data.csv")

regions = makerSpaceRdd \
.filter(lambda line: Utils.COMMA_DELIMITER.split(line)[0] != "Timestamp") \
.map(lambda line:next((postCodeMap[prefix] for prefix in getPostPrefixes(line) \
ifprefix in postCodeMap),"Unknow"))
.map(lambda line: postCodeMap[getPostPrefix(line)] \
ifgetPostPrefix(line) in postCodeMap else"Unknow")

for region, count in regions.countByValue().items():
print("{} : {}".format(region, count))
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
from pyspark import SparkContext
from pyspark import SparkContext, SparkConf

if __name__ == "__main__":

sc = SparkContext("local", "AverageHousePrice")
sc.setLogLevel("ERROR")
conf = SparkConf().setAppName("AverageHousePrice").setMaster("local")
sc = SparkContext(conf = conf)

lines = sc.textFile("in/RealEstate.csv")
cleanedLines = lines.filter(lambda line: "Bedrooms" not in line)
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,26 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from pairRdd.aggregation.reducebykey.housePrice.AvgCount import AvgCount

if __name__ == "__main__":

sc = SparkContext("local", "avgHousePrice")
sc.setLogLevel("ERROR")
conf = SparkConf().setAppName("avgHousePrice").setMaster("local[3]")
sc = SparkContext(conf = conf)

lines = sc.textFile("in/RealEstate.csv")
cleanedLines = lines.filter(lambda line: "Bedrooms" not in line)

housePricePairRdd = cleanedLines.map(lambda line: \
(line.split(",")[3], (1, float(line.split(",")[2]))))
(line.split(",")[3],AvgCount(1, float(line.split(",")[2]))))

housePriceTotal = housePricePairRdd \
.reduceByKey(lambda x, y:(x[0] + y[0], x[1] + y[1]))
.reduceByKey(lambda x, y:AvgCount(x.count + y.count, x.total + y.total))

print("housePriceTotal: ")
for bedroom,total in housePriceTotal.collect():
print("{} :{}".format(bedroom, total))
for bedroom,avgCount in housePriceTotal.collect():
print("{} :({}, {})".format(bedroom,avgCount.count, avgCount.total))

housePriceAvg = housePriceTotal.mapValues(lambda avgCount: avgCount[1] / avgCount[0])
housePriceAvg = housePriceTotal.mapValues(lambda avgCount: avgCount.total / avgCount.count)
print("\nhousePriceAvg: ")
for bedroom, avg in housePriceAvg.collect():
print("{} : {}".format(bedroom, avg))
8 changes: 5 additions & 3 deletionspairRdd/filter/AirportsNotInUsaSolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

if __name__ == "__main__":

sc =SparkContext("local", "airports")
sc.setLogLevel("ERROR")
conf =SparkConf().setAppName("airports").setMaster("local[*]")
sc = SparkContext(conf = conf)

airportsRDD = sc.textFile("in/airports.text")

Expand Down
10 changes: 6 additions & 4 deletionspairRdd/groupbykey/AirportsByCountrySolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

if __name__ == "__main__":

sc =SparkContext("local", "airports")
sc.setLogLevel("ERROR")
conf =SparkConf().setAppName("airports").setMaster("local[*]")
sc = SparkContext(conf = conf)

lines = sc.textFile("in/airports.text")

Expand All@@ -15,4 +17,4 @@
airportsByCountry = countryAndAirportNameAndPair.groupByKey()

for country, airportName in airportsByCountry.collectAsMap().items():
print("{}: {}".format(country,list(airportName)))
print("{}: {}".format(country,list(airportName)))
9 changes: 5 additions & 4 deletionspairRdd/mapValues/AirportsUppercaseSolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

if __name__ == "__main__":

sc = SparkContext("local", "airports")
sc.setLogLevel("ERROR")
conf = SparkConf().setAppName("airports").setMaster("local[*]")
sc = SparkContext(conf = conf)

airportsRDD = sc.textFile("in/airports.text")

Expand Down
10 changes: 5 additions & 5 deletionspairRdd/sort/AverageHousePriceSolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import sys
sys.path.insert(0, '.')
from pairRdd.aggregation.reducebykey.housePrice.AvgCount import AvgCount
from pyspark import SparkContext

from pyspark import SparkContext, SparkConf

if __name__ == "__main__":

sc = SparkContext("local", "averageHousePriceSolution")
sc.setLogLevel("ERROR")
conf = SparkConf().setAppName("averageHousePriceSolution").setMaster("local[*]")
sc = SparkContext(conf = conf)

lines = sc.textFile("in/RealEstate.csv")
cleanedLines = lines.filter(lambda line: "Bedrooms" not in line)
Expand Down
7 changes: 5 additions & 2 deletionsrdd/airports/AirportsByLatitudeSolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

def splitComma(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
return "{}, {}".format(splits[1], splits[6])

if __name__ == "__main__":
sc = SparkContext("local", "airports")
conf = SparkConf().setAppName("airports").setMaster("local[*]")
sc = SparkContext(conf = conf)

airports = sc.textFile("in/airports.text")

Expand Down
7 changes: 5 additions & 2 deletionsrdd/airports/AirportsInUsaSolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
from pyspark import SparkContext
import sys
sys.path.insert(0, '.')
from pyspark import SparkContext, SparkConf
from commons.Utils import Utils

def splitComma(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
return "{}, {}".format(splits[1], splits[2])

if __name__ == "__main__":
sc = SparkContext("local", "airports")
conf = SparkConf().setAppName("airports").setMaster("local[*]")
sc = SparkContext(conf = conf)

airports = sc.textFile("in/airports.text")
airportsInUSA = airports.filter(lambda line : Utils.COMMA_DELIMITER.split(line)[3] == "\"United States\"")
Expand Down
3 changes: 3 additions & 0 deletionsrdd/count/CountExample.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,9 +3,12 @@
if __name__ == "__main__":
conf = SparkConf().setAppName("count").setMaster("local[*]")
sc = SparkContext(conf = conf)

inputWords = ["spark", "hadoop", "spark", "hive", "pig", "cassandra", "hadoop"]

wordRdd = sc.parallelize(inputWords)
print("Count: {}".format(wordRdd.count()))

worldCountByValue = wordRdd.countByValue()
print("CountByValue: ")
for word, count in worldCountByValue.items():
Expand Down
13 changes: 7 additions & 6 deletionssparkSql/HousePriceProblem.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,21 @@
Create a Spark program to read the house data from in/RealEstate.csv,
group by location, aggregate the average price per SQ Ft and sort by average price per SQ Ft.

The houses dataset contains a collection of recent real estate listings in San Luis Obispo county and
around it. 
The houses dataset contains a collection of recent real estate listings in 
San Luis Obispo county andaround it. 

The dataset contains the following fields:
1. MLS: Multiple listing service number for the house (unique ID).
2. Location: city/town where the house is located. Most locations are in San Luis Obispo county and
northern Santa Barbara county (Santa Maria­Orcutt, Lompoc, Guadelupe, Los Alamos), but there
some out of area locations as well.
2. Location: city/town where the house is located. Most locations are in 
San Luis Obispo county andnorthern Santa Barbara county (Santa Maria­Orcutt, Lompoc, 
Guadelupe, Los Alamos), but theresome out of area locations as well.
3. Price: the most recent listing price of the house (in dollars).
4. Bedrooms: number of bedrooms.
5. Bathrooms: number of bathrooms.
6. Size: size of the house in square feet.
7. Price/SQ.ft: price of the house per square foot.
8. Status: type of sale. Thee types are represented in the dataset: Short Sale, Foreclosure and Regular.
8. Status: type of sale. Thee types are represented in the dataset: Short Sale, 
Foreclosure and Regular.

Each field is comma separated.

Expand Down
4 changes: 2 additions & 2 deletionssparkSql/HousePriceSolution.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,8 @@

if __name__ == "__main__":

session = SparkSession.builder.appName("HousePriceSolution").master("local").getOrCreate()
session.sparkContext.setLogLevel("ERROR")
session = SparkSession.builder.appName("HousePriceSolution").master("local[*]").getOrCreate()

realEstate = session.read \
.option("header","true") \
.option("inferSchema", value=True) \
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp