PySpark SQL 函數的 collect_set(~)
方法返回列中的一組唯一值。空值將被忽略。
注意
使用 collect_list(~)
來獲取允許重複的值列表。
參數
1.col
| string
或 Column
對象
列標簽或 Column
對象。
返回值
PySpark SQL Column
對象 ( pyspark.sql.column.Column
)。
警告
假設返回集合的順序可能是隨機的,因為順序受到洗牌操作的影響。
例子
考慮以下PySpark DataFrame:
data = [("Alex", "A"), ("Alex", "B"), ("Bob", "A"), ("Cathy", "C"), ("Dave", None)]
df = spark.createDataFrame(data, ["name", "group"])
df.show()
+-----+-----+
| name|group|
+-----+-----+
| Alex| A|
| Alex| B|
| Bob| A|
|Cathy| C|
| Dave| null|
+-----+-----+
獲取 PySpark 中的一組列值
要獲取 group
列中唯一的一組值:
import pyspark.sql.functions as F
df.select(F.collect_set("group")).show()
+------------------+
|collect_set(group)|
+------------------+
| [C, B, A]|
+------------------+
同樣,您也可以將 Column
對象傳遞給 collect_set(~)
:
import pyspark.sql.functions as F
df.select(F.collect_set(df.group)).show()
+------------------+
|collect_set(group)|
+------------------+
| [C, B, A]|
+------------------+
請注意null
值沒有出現在結果集中。
將集合作為標準列表
要將集合作為標準列表:
list_rows = df.select(F.collect_set(df.group)).collect()
list_rows[0][0]
['C', 'B', 'A']
這裏,PySpark DataFrame 的 collect()
方法返回Row
對象的列表。由於 collect_set(~)
的性質,該列表保證長度為一。 Row
對象包含該列表,因此我們需要包含另一個 [0]
。
獲取PySpark中每個組的一組列值
方法 collect_set(~)
通常在聚合上下文中使用。考慮與之前相同的 PySpark DataFrame:
df.show()
+-----+-----+
| name|group|
+-----+-----+
| Alex| A|
| Alex| B|
| Bob| A|
|Cathy| C|
| Dave| null|
+-----+-----+
要將 group
列展平為每個 name
的單個集合:
import pyspark.sql.functions as F
df.groupby("name").agg(F.collect_set("group")).show()
+-----+------------------+
| name|collect_set(group)|
+-----+------------------+
| Alex| [B, A]|
| Bob| [A]|
|Cathy| [C]|
+-----+------------------+
相關用法
- Python PySpark SQL Functions collect_list方法用法及代碼示例
- Python PySpark SQL Functions col方法用法及代碼示例
- Python PySpark SQL Functions concat方法用法及代碼示例
- Python PySpark SQL Functions count_distinct方法用法及代碼示例
- Python PySpark SQL Functions concat_ws方法用法及代碼示例
- Python PySpark SQL Functions countDistinct方法用法及代碼示例
- Python PySpark SQL Functions count方法用法及代碼示例
- Python PySpark SQL Functions split方法用法及代碼示例
- Python PySpark SQL Functions repeat方法用法及代碼示例
- Python PySpark SQL Functions explode方法用法及代碼示例
- Python PySpark SQL Functions instr方法用法及代碼示例
- Python PySpark SQL Functions dayofmonth方法用法及代碼示例
- Python PySpark SQL Functions date_add方法用法及代碼示例
- Python PySpark SQL Functions array方法用法及代碼示例
- Python PySpark SQL Functions translate方法用法及代碼示例
- Python PySpark SQL Functions dayofweek方法用法及代碼示例
- Python PySpark SQL Functions expr方法用法及代碼示例
- Python PySpark SQL Functions regexp_extract方法用法及代碼示例
- Python PySpark SQL Functions regexp_replace方法用法及代碼示例
- Python PySpark SQL Functions round方法用法及代碼示例
- Python PySpark SQL Functions date_format方法用法及代碼示例
- Python PySpark SQL Functions lit方法用法及代碼示例
- Python PySpark SQL Functions upper方法用法及代碼示例
- Python PySpark SQL Functions length方法用法及代碼示例
- Python PySpark SQL Functions dayofyear方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 PySpark SQL Functions | collect_set method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。