Extract Transform Select

Introdução ao Spark SQL em Python

Mark Plutowski

Data Scientist

ETS

Introdução ao Spark SQL em Python

Extrair Transformar Selecionar

Introdução ao Spark SQL em Python

Extrair, Transformar e Selecionar

  • Extração
  • Transformação
  • Seleção
Introdução ao Spark SQL em Python

Funções nativas

from pyspark.sql.functions import split, explode
Introdução ao Spark SQL em Python

A função length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Introdução ao Spark SQL em Python

Criando uma função personalizada

  • Função Definida pelo Usuário
  • UDF
Introdução ao Spark SQL em Python

Importando a função udf

from pyspark.sql.functions import udf
Introdução ao Spark SQL em Python

Criando uma UDF booleana

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Introdução ao Spark SQL em Python

Criando uma UDF booleana

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|
+--------+
Introdução ao Spark SQL em Python

Tipos de retorno importantes de UDF

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introdução ao Spark SQL em Python

Criando uma UDF de 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]|
+-----------------------------+----------------------+
Introdução ao Spark SQL em Python

Criando uma UDF de 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()))
Introdução ao Spark SQL em Python

Formato de vetor esparso

  1. Índices
  2. Valores

Exemplo:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Vetor esparso: (4, [0, 3], [1.0, 3.0])
Introdução ao Spark SQL em Python

Trabalhando com dados de vetor

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introdução ao Spark SQL em Python

Vamos praticar!

Introdução ao Spark SQL em Python

Preparing Video For Download...