資料框:
from pyspark.sql import functions as F
df = spark.createDataFrame([([(1, 2), (3, 4)],)], 'col_name array<struct<c1:int,c2:int>>')
df.show()
# ----------------
# | col_name|
# ----------------
# |[{1, 2}, {3, 4}]|
# ----------------
df.printSchema()
# root
# |-- col_name: array (nullable = true)
# | |-- element: struct (containsNull = true)
# | | |-- c1: integer (nullable = true)
# | | |-- c2: integer (nullable = true)
Iexplode陣列(結果是型別的列struct<c1:int,c2:int>)。
然后選擇每個結構欄位(但我select兩次):
df = df.select(
F.explode('col_name')
).select(
[f'col.{c}' for c in ('c1', 'c2')]
)
df.show()
# --- ---
# | c1| c2|
# --- ---
# | 1| 2|
# | 3| 4|
# --- ---
df.printSchema()
# root
# |-- c1: integer (nullable = true)
# |-- c2: integer (nullable = true)
我知道我可以將第二個選擇縮短為 just 'col.*'。但我仍然有 2 個選擇。
問題。有沒有一種方法可以在爆炸后立即選擇結構欄位,只有 1 個選擇?
由于爆炸的結果有 schema struct<c1:int,c2:int>,我認為這會起作用......
df = df.select(
[F.explode('col_name')[c] for c in ('c1', 'c2')]
)
AnalysisException:col 中沒有這樣的結構欄位 c1
uj5u.com熱心網友回復:
使用魔法行內
df.selectExpr('inline(col_name)').show()
--- ---
| c1| c2|
--- ---
| 1| 2|
| 3| 4|
--- ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497518.html
標籤:阿帕奇火花 pyspark 结构 apache-spark-sql 爆炸
下一篇:計算視窗中過濾值的出現次數
