PySpark SQL 函數的 explode(~) 方法會展平 list 或 dictionary 類型的指定列值。
參數
1.col | string 或 Column
包含要展平的列表或字典的列。
返回值
新的 PySpark 列。
例子
展平列表
考慮以下PySpark DataFrame:
df = spark.createDataFrame([[['a','b']],[['d']]], ['vals'])
df.show()
+------+
|  vals|
+------+
|[a, b]|
|   [d]|
+------+這裏,vals 列包含列表。
要展平 vals 列中的列表,請使用 explode(~) 方法:
import pyspark.sql.functions as F
df.select(F.explode('vals').alias('exploded')).show()
+--------+
|exploded|
+--------+
|       a|
|       b|
|       d|
+--------+在這裏,我們使用  alias(~)  方法為 explode(~) 返回的列分配標簽。
扁平化字典
考慮以下PySpark DataFrame:
df = spark.createDataFrame([[{'a':'b'}],[{'c':'d','e':'f'}]], ['vals'])
df.show()
+----------------+
|            vals|
+----------------+
|        {a -> b}|
|{e -> f, c -> d}|
+----------------+這裏,vals 列包含字典。
要展平 vals 列中的每個字典,請使用 explode(~) 方法:
df.select(F.explode('vals').alias('exploded_key', 'exploded_val')).show()
+------------+------------+
|exploded_key|exploded_val|
+------------+------------+
|           a|           b|
|           e|           f|
|           c|           d|
+------------+------------+對於字典,explode(~) 方法返回兩列 - 第一列包含所有鍵,第二列包含所有值。
相關用法
- Python PySpark SQL Functions expr方法用法及代碼示例
- Python PySpark SQL Functions element_at方法用法及代碼示例
- Python PySpark SQL Functions split方法用法及代碼示例
- Python PySpark SQL Functions repeat方法用法及代碼示例
- Python PySpark SQL Functions concat方法用法及代碼示例
- Python PySpark SQL Functions instr方法用法及代碼示例
- Python PySpark SQL Functions count_distinct方法用法及代碼示例
- Python PySpark SQL Functions dayofmonth方法用法及代碼示例
- Python PySpark SQL Functions date_add方法用法及代碼示例
- Python PySpark SQL Functions array方法用法及代碼示例
- Python PySpark SQL Functions concat_ws方法用法及代碼示例
- Python PySpark SQL Functions col方法用法及代碼示例
- Python PySpark SQL Functions translate方法用法及代碼示例
- Python PySpark SQL Functions dayofweek方法用法及代碼示例
- Python PySpark SQL Functions regexp_extract方法用法及代碼示例
- Python PySpark SQL Functions regexp_replace方法用法及代碼示例
- Python PySpark SQL Functions round方法用法及代碼示例
- Python PySpark SQL Functions countDistinct方法用法及代碼示例
- Python PySpark SQL Functions date_format方法用法及代碼示例
- Python PySpark SQL Functions collect_list方法用法及代碼示例
- Python PySpark SQL Functions lit方法用法及代碼示例
- Python PySpark SQL Functions upper方法用法及代碼示例
- Python PySpark SQL Functions length方法用法及代碼示例
- Python PySpark SQL Functions dayofyear方法用法及代碼示例
- Python PySpark SQL Functions trim方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 PySpark SQL Functions | explode method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
