提取 转换 选择

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 入门

创建自定义函数

  • 用户自定义函数(User Defined Function)
  • 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. 索引

示例:

  • 数组:[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 入门

¡Vamos a practicar!

Python 中的 Spark SQL 入门

Preparing Video For Download...