Extract Transform Select

Introduction to Spark SQL in Python

Mark Plutowski

Data Scientist

ETS

Introduction to Spark SQL in Python

Extract Transform Select

Introduction to Spark SQL in Python

Extract, Transform และ Select

  • การดึงข้อมูล (Extraction)
  • การแปลงข้อมูล (Transformation)
  • การเลือกข้อมูล (Selection)
Introduction to Spark SQL in Python

ฟังก์ชันในตัว

from pyspark.sql.functions import split, explode
Introduction to Spark SQL in Python

ฟังก์ชัน length

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

การสร้างฟังก์ชันแบบกำหนดเอง

  • User Defined Function
  • UDF
Introduction to Spark SQL in Python

การนำเข้าฟังก์ชัน udf

from pyspark.sql.functions import udf
Introduction to Spark SQL in Python

การสร้าง UDF แบบ boolean

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

การสร้าง 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|
+--------+
Introduction to Spark SQL in Python

ประเภทค่าที่คืนจาก UDF ที่ควรรู้จัก

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Introduction to Spark SQL in Python

การสร้าง 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]|
+-----------------------------+----------------------+
Introduction to Spark SQL in Python

การสร้าง 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()))
Introduction to Spark SQL in Python

รูปแบบ sparse vector

  1. ดัชนี (Indices)
  2. ค่า (Values)

ตัวอย่าง:

  • Array: [1.0, 0.0, 0.0, 3.0]
  • Sparse vector: (4, [0, 3], [1.0, 3.0])
Introduction to Spark SQL in Python

การทำงานกับข้อมูลเวกเตอร์

  • hasattr(x, "toArray")
  • x.numNonzeros())
Introduction to Spark SQL in Python

มาฝึกกันเถอะ!

Introduction to Spark SQL in Python

Preparing Video For Download...