Trích xuất, Biến đổi, Chọn

Nhập môn Spark SQL bằng Python

Mark Plutowski

Data Scientist

ETS

Nhập môn Spark SQL bằng Python

Trích xuất Biến đổi Chọn

Nhập môn Spark SQL bằng Python

Trích xuất, Biến đổi, và Chọn

  • Trích xuất
  • Biến đổi
  • Chọn
Nhập môn Spark SQL bằng Python

Hàm tích hợp sẵn

from pyspark.sql.functions import split, explode
Nhập môn Spark SQL bằng Python

Hàm length

from pyspark.sql.functions import length
df.where(length('sentence') == 0)
Nhập môn Spark SQL bằng Python

Tạo hàm tùy chỉnh

  • Hàm do người dùng định nghĩa (User Defined Function)
  • UDF
Nhập môn Spark SQL bằng Python

Import hàm udf

from pyspark.sql.functions import udf
Nhập môn Spark SQL bằng Python

Tạo UDF kiểu boolean

print(df)
DataFrame[textdata: string]
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
Nhập môn Spark SQL bằng Python

Tạo UDF kiểu 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|
+--------+
Nhập môn Spark SQL bằng Python

Kiểu trả về UDF quan trọng

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Nhập môn Spark SQL bằng Python

Tạo UDF mảng

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]|
+-----------------------------+----------------------+
Nhập môn Spark SQL bằng Python

Tạo UDF mảng

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()))
Nhập môn Spark SQL bằng Python

Định dạng vector thưa

  1. Chỉ số
  2. Giá trị

Ví dụ:

  • Mảng: [1.0, 0.0, 0.0, 3.0]
  • Vector thưa: (4, [0, 3], [1.0, 3.0])
Nhập môn Spark SQL bằng Python

Làm việc với dữ liệu vector

  • hasattr(x, "toArray")
  • x.numNonzeros())
Nhập môn Spark SQL bằng Python

Ayo berlatih!

Nhập môn Spark SQL bằng Python

Preparing Video For Download...