Extragere Transformare Selectare

Introducere în Spark SQL în Python

Mark Plutowski

Data Scientist

ETS

Introducere în Spark SQL în Python

Extragere Transformare Selectare

Introducere în Spark SQL în Python

Extragere, Transformare și Selectare

  • Extragere
  • Transformare
  • Selectare
Introducere în Spark SQL în Python

Funcții încorporate

from pyspark.sql.functions import split, explode
Introducere în Spark SQL în Python

Funcția length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Introducere în Spark SQL în Python

Crearea unei funcții personalizate

  • Funcție definită de utilizator
  • UDF
Introducere în Spark SQL în Python

Importarea funcției udf

from pyspark.sql.functions import udf
Introducere în Spark SQL în Python

Crearea unui UDF boolean

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Introducere în Spark SQL în Python

Crearea unui UDF boolean

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|
+--------+
Introducere în Spark SQL în Python

Tipuri de returnare importante pentru UDF

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introducere în Spark SQL în Python

Crearea unui UDF de tip array

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]|
+-----------------------------+----------------------+
Introducere în Spark SQL în Python

Crearea unui UDF de tip array

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()))
Introducere în Spark SQL în Python

Formatul vectorului rar

  1. Indici
  2. Valori

Exemplu:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Vector rar: (4, [0, 3], [1.0, 3.0])
Introducere în Spark SQL în Python

Lucrul cu date de tip vector

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introducere în Spark SQL în Python

Să exersăm!

Introducere în Spark SQL în Python

Preparing Video For Download...