Extraire Transformer Sélectionner

Introduction à Spark SQL en Python

Mark Plutowski

Data Scientist

ETS

Introduction à Spark SQL en Python

Extraire Transformer Sélectionner

Introduction à Spark SQL en Python

Extraire, transformer et sélectionner

  • Extraction
  • Transformation
  • Sélection
Introduction à Spark SQL en Python

Fonctions intégrées

from pyspark.sql.functions import split, explode
Introduction à Spark SQL en Python

La fonction length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Introduction à Spark SQL en Python

Créer une fonction personnalisée

  • User Defined Function
  • UDF
Introduction à Spark SQL en Python

Importer la fonction udf

from pyspark.sql.functions import udf
Introduction à Spark SQL en Python

Créer une UDF booléenne

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Introduction à Spark SQL en Python

Créer une UDF booléenne

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|
+--------+
Introduction à Spark SQL en Python

Types de retour UDF importants

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introduction à Spark SQL en Python

Créer une UDF de type tableau

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]|
+-----------------------------+----------------------+
Introduction à Spark SQL en Python

Créer une UDF de type tableau

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()))
Introduction à Spark SQL en Python

Format d'un vecteur creux

  1. Indices
  2. Valeurs

Exemple :

  • Tableau : [1.0, 0.0, 0.0, 3.0]
  • Vecteur creux : (4, [0, 3], [1.0, 3.0])
Introduction à Spark SQL en Python

Travailler avec des données vectorielles

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introduction à Spark SQL en Python

Passons à la pratique !

Introduction à Spark SQL en Python

Preparing Video For Download...