Extract Transform Select

Introductie tot Spark SQL in Python

Mark Plutowski

Data Scientist

ETS

Introductie tot Spark SQL in Python

Extract Transform Selec

Introductie tot Spark SQL in Python

Extract, Transform en Select

  • Extractie
  • Transformatie
  • Selectie
Introductie tot Spark SQL in Python

Ingebouwde functies

from pyspark.sql.functions import split, explode
Introductie tot Spark SQL in Python

De functie length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Introductie tot Spark SQL in Python

Een eigen functie maken

  • User Defined Function
  • UDF
Introductie tot Spark SQL in Python

De functie udf importeren

from pyspark.sql.functions import udf
Introductie tot Spark SQL in Python

Een boolean UDF maken

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Introductie tot Spark SQL in Python

Een boolean UDF maken

short_udf = udf(lambda x: 
                          True if not x or len(x) < 10 else False, 
                          BooleanType())
df.select(short_udf('textdata')\
  .alias("is short"))\
  .show(3)
+--------+
|is short|
+--------+
|   false|
|    true|
|   false|
+--------+
Introductie tot Spark SQL in Python

Belangrijke UDF-returntypes

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introductie tot Spark SQL in Python

Een array-UDF maken

df3.select('word array', in_udf('word array').alias('without endword'))\
   .show(5, truncate=30)
+-----------------------------+----------------------+
|                   word array|       without endword|
+-----------------------------+----------------------+
|[then, how, many, are, there]|[then, how, many, are]|
|                  [how, many]|                 [how]|
|             [i, donot, know]|            [i, donot]|
|                  [quite, so]|               [quite]|
|   [you, have, not, observed]|      [you, have, not]|
+-----------------------------+----------------------+
Introductie tot Spark SQL in Python

Een array-UDF maken

from pyspark.sql.types import StringType, ArrayType
# Removes last item in array
in_udf = udf(lambda x: 
    x[0:len(x)-1] if x and len(x) > 1 
    else [], 
    ArrayType(StringType()))
Introductie tot Spark SQL in Python

Formaat van sparse vector

  1. Indexen
  2. Waarden

Voorbeeld:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Sparse vector: (4, [0, 3], [1.0, 3.0])
Introductie tot Spark SQL in Python

Werken met vectordata

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introductie tot Spark SQL in Python

Laten we oefenen!

Introductie tot Spark SQL in Python

Preparing Video For Download...