Extraer Transformar Seleccionar

Introducción a Spark SQL en Python

Mark Plutowski

Data Scientist

ETS

Introducción a Spark SQL en Python

Extract Transform Selec

Introducción a Spark SQL en Python

Extraer, transformar y seleccionar

  • Extracción
  • Transformación
  • Selección
Introducción a Spark SQL en Python

Funciones integradas

from pyspark.sql.functions import split, explode
Introducción a Spark SQL en Python

La función length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Introducción a Spark SQL en Python

Crear una función personalizada

  • Función definida por el usuario
  • UDF
Introducción a Spark SQL en Python

Importar la función udf

from pyspark.sql.functions import udf
Introducción a Spark SQL en Python

Crear un UDF booleano

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Introducción a Spark SQL en Python

Crear un UDF booleano

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|
+--------+
Introducción a Spark SQL en Python

Tipos de retorno clave para UDF

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introducción a Spark SQL en Python

Crear un UDF de arrays

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]|
+-----------------------------+----------------------+
Introducción a Spark SQL en Python

Crear un UDF de arrays

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()))
Introducción a Spark SQL en Python

Formato de vector disperso

  1. Índices
  2. Valores

Ejemplo:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Vector disperso: (4, [0, 3], [1.0, 3.0])
Introducción a Spark SQL en Python

Trabajar con datos vectoriales

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introducción a Spark SQL en Python

¡Vamos a practicar!

Introducción a Spark SQL en Python

Preparing Video For Download...