擷取 轉換 篩選

Python Spark SQL 入門

Mark Plutowski

Data Scientist

ETS

Python Spark SQL 入門

擷取 轉換 篩選

Python Spark SQL 入門

擷取、轉換與篩選

  • 擷取
  • 轉換
  • 篩選
Python Spark SQL 入門

內建函式

from pyspark.sql.functions import split, explode
Python Spark SQL 入門

length 函式

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

建立自訂函式

  • 使用者自訂函式
  • UDF
Python Spark SQL 入門

匯入 udf 函式

from pyspark.sql.functions import udf
Python Spark SQL 入門

建立布林 UDF

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

建立布林 UDF

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|
+--------+
Python Spark SQL 入門

常用 UDF 回傳型別

from pyspark.sql.types import StringType, IntegerType, FloatType, ArrayType
Python Spark SQL 入門

建立陣列 UDF

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]|
+-----------------------------+----------------------+
Python Spark SQL 入門

建立陣列 UDF

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()))
Python Spark SQL 入門

稀疏向量格式

  1. 索引
  2. 數值

範例:

  • 陣列:[1.0, 0.0, 0.0, 3.0]
  • 稀疏向量:(4, [0, 3], [1.0, 3.0])
Python Spark SQL 入門

操作向量資料

  • hasattr(x, "toArray")
  • x.numNonzeros())
Python Spark SQL 入門

一起來練習吧!

Python Spark SQL 入門

Preparing Video For Download...