Extract Transform Select

Pengantar Spark SQL dalam Python

Mark Plutowski

Data Scientist

ETS

Pengantar Spark SQL dalam Python

Extract Transform Selec

Pengantar Spark SQL dalam Python

Ekstrak, Transformasi, dan Seleksi

  • Ekstraksi
  • Transformasi
  • Seleksi
Pengantar Spark SQL dalam Python

Fungsi bawaan

from pyspark.sql.functions import split, explode
Pengantar Spark SQL dalam Python

Fungsi length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Pengantar Spark SQL dalam Python

Membuat fungsi kustom

  • User Defined Function
  • UDF
Pengantar Spark SQL dalam Python

Mengimpor fungsi udf

from pyspark.sql.functions import udf
Pengantar Spark SQL dalam Python

Membuat UDF boolean

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

Membuat 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|
+--------+
Pengantar Spark SQL dalam Python

Tipe keluaran UDF penting

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Pengantar Spark SQL dalam Python

Membuat UDF 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]|
+-----------------------------+----------------------+
Pengantar Spark SQL dalam Python

Membuat UDF 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()))
Pengantar Spark SQL dalam Python

Format vektor jarang

  1. Indeks
  2. Nilai

Contoh:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Vektor jarang: (4, [0, 3], [1.0, 3.0])
Pengantar Spark SQL dalam Python

Bekerja dengan data vektor

  • hasattr(x, "toArray")
  • x.numNonzeros())
Pengantar Spark SQL dalam Python

Ayo berlatih!

Pengantar Spark SQL dalam Python

Preparing Video For Download...