Extract Transform Select

Introduktion till Spark SQL i Python

Mark Plutowski

Data Scientist

ETS

Introduktion till Spark SQL i Python

Extract Transform Select

Introduktion till Spark SQL i Python

Extrahera, transformera och selektera

  • Extraktion
  • Transformation
  • Selektion
Introduktion till Spark SQL i Python

Inbyggda funktioner

from pyspark.sql.functions import split, explode
Introduktion till Spark SQL i Python

Funktionen length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Introduktion till Spark SQL i Python

Skapa en anpassad funktion

  • User Defined Function
  • UDF
Introduktion till Spark SQL i Python

Importera udf-funktionen

from pyspark.sql.functions import udf
Introduktion till Spark SQL i Python

Skapa en boolesk UDF

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Introduktion till Spark SQL i Python

Skapa en boolesk UDF

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|
+--------+
Introduktion till Spark SQL i Python

Viktiga returtyper för UDF

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introduktion till Spark SQL i Python

Skapa en array-UDF

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]|
+-----------------------------+----------------------+
Introduktion till Spark SQL i Python

Skapa en array-UDF

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()))
Introduktion till Spark SQL i Python

Format för gles vektor

  1. Index
  2. Värden

Exempel:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Gles vektor: (4, [0, 3], [1.0, 3.0])
Introduktion till Spark SQL i Python

Arbeta med vektordata

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introduktion till Spark SQL i Python

Nu kör vi en övning!

Introduktion till Spark SQL i Python

Preparing Video For Download...