我們如何在 Spark SQL 中有條件地分解多個陣列列?
我的輸入如下所示:
col_1 col2 col3
123 ["id_1","id_2"] ["tim","steve"]
456 ["id_3","id_4"] ["jenny"]
我需要將其轉換為:
- 具有相同索引的陣列項映射到同一行
- 如果 中只有 1 個條目
col3,則適用于每一行
輸出應如下所示:
col_1 col2 col3
123 id_1 tim
123 id_2 steve
456 id_3 jenny
456 id_4 jenny
我嘗試了各種分解視圖和橫向視圖的組合,但每個組合都回傳了與所需不匹配的行組合或錯誤訊息。
df = spark.createDataFrame(
[
(123, ["id_1", "id_2"], ["tim", "steve"]),
(456, ["id_3", "id_4"], ["jenny"]),
],
["col1", "col2", "col3"]
)
df.createOrReplaceTempView("my_table")
spark.sql("""
select
col1,
col1_d,
col2_d
from my_table
lateral view explode(col2) exploded_col as col1_d
lateral view explode(col3) exploded_col_2 as col2_d
""").show()
---- ------ ------
|col1|col1_d|col2_d|
---- ------ ------
| 123| id_1| tim|
| 123| id_1| steve|
| 123| id_2| tim|
| 123| id_2| steve|
| 456| id_3| jenny|
| 456| id_4| jenny|
---- ------ ------
uj5u.com熱心網友回復:
假設資料已針對以下條件正確驗證:
- 如果 "col3" > 1,則 len("col2") == len("col3")
- 或 "col3" == 1
array_repeat您可以通過對 len("col2") 重復“col3”的函式來實作這一點。對于“col2”為空的極端情況,只需將其轉換為空陣列:
df = df.withColumn("col3",
F.when((F.size("col2") > 0)&(F.size("col3") == 1), F.array_repeat(F.element_at("col3", 1), F.size("col2"))) \
.otherwise(F.col("col3")) \
)
df = df.withColumn("col2",
F.when((F.col("col2").isNull())|(F.size("col2") == 0), F.array(F.lit(""))) \
.otherwise(F.col("col2")) \
)
---- ------------ --------------
|col1| col2| col3|
---- ------------ --------------
| 123|[id_1, id_2]| [tim, steve]|
| 456|[id_3, id_4]|[jenny, jenny]|
| 789| []| [harry]|
---- ------------ --------------
arrays_zip然后使用和 finally一起壓縮“col2”和“col3” explode:
df = df \
.withColumn("col2_col3", F.explode(F.arrays_zip("col2", "col3"))) \
.select("col1", F.col("col2_col3.col2").alias("col2"), F.col("col2_col3.col3").alias("col3"))
---- ---- -----
|col1|col2| col3|
---- ---- -----
| 123|id_1| tim|
| 123|id_2|steve|
| 456|id_3|jenny|
| 456|id_4|jenny|
| 789| |harry|
---- ---- -----
使用的資料集:
df = spark.createDataFrame(
[
(123, ["id_1", "id_2"], ["tim", "steve"]),
(456, ["id_3", "id_4"], ["jenny"]),
(789, None, ["harry"]),
],
["col1", "col2", "col3"]
)
---- ------------ ------------
|col1| col2| col3|
---- ------------ ------------
| 123|[id_1, id_2]|[tim, steve]|
| 456|[id_3, id_4]| [jenny]|
| 789| null| [harry]|
---- ------------ ------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522039.html
上一篇:為什么我們在累加器中使用Val而不是在scala中使用Var?
下一篇:磁區增量表無法寫入檢查點?
