練習陣列欄位
已提供 SQL 函式 udf,同時也提供了名為 df_before 的資料框,型別為 DataFrame[doc: array<string>, in: array<string>, out: array<string>]。
變數 TRIVIAL_TOKENS 是一個 set,裡面包含我們想要移除的特定單字。
本練習屬於課程
Python Spark SQL 入門
練習說明
- 顯示
df_before中doc含有項目5的列。 - 建立一個 udf,從陣列欄位中移除出現在
TRIVIAL_TOKENS的項目。順序不需要保留。 - 在
df2中,將in與out欄位裡出現在TRIVIAL_TOKENS的標記移除。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Show the rows where doc contains the item '5'
df_before.where(array_contains('doc', '____')).show()
# UDF removes items in TRIVIAL_TOKENS from array
rm_trivial_udf = udf(lambda x:
list(set(x) - ____) if x
else x,
ArrayType(____()))
# Remove trivial tokens from 'in' and 'out' columns of df2
df_after = df_before.withColumn('in', ____('in'))\
.withColumn('out', ____('out'))
# Show the rows of df_after where doc contains the item '5'
df_after.where(array_contains('doc','5')).show()