PySpark SQL 函數的count_distinct(~) 方法計算指定列中不同值的數量。
參數
1.*cols | string 或 Column
用於計算不同值數量的列。
返回值
PySpark Column 保存一個整數。
例子
考慮以下PySpark DataFrame:
df = spark.createDataFrame([["Alex", "A"], ["Bob", "A"], ["Cathy", "B"]], ["name", "class"])
df.show()
+-----+-----+
| name|class|
+-----+-----+
| Alex|    A|
|  Bob|    A|
|Cathy|    B|
+-----+-----+計算PySpark中單列中不同值的數量
要計算 class 列中不同值的數量:
from pyspark.sql import functions as F
df.select(F.count_distinct("class").alias("c")).show()
+---+
|  c|
+---+
|  2|
+---+在這裏,我們將名稱 "c" 賦予 count_distinct(~) 通過 alias(~) 返回的 Column。
請注意,我們還可以向 count_distinct(~) 提供 Column 對象:
df.select(F.count_distinct(df["class"]).alias("c")).show()
+---+
|  c|
+---+
|  2|
+---+獲取整數計數
默認情況下, count_distinct(~) 返回 PySpark Column 。要獲取整數計數:
df.select(F.count_distinct(df["class"])).collect()[0][0]
2在這裏,我們使用 select(~) 方法將Column轉換為PySpark DataFrame。然後,我們使用 collect(~) 方法將DataFrame轉換為Row對象列表。由於此列表中隻有一個 Row 以及 Row 中的一個值,因此我們使用 [0][0] 來訪問整數計數。
計算 PySpark 中一組列中不同值的數量
要計算列 name 和 class 的不同值的數量:
df.select(F.count_distinct("name", "class").alias("c")).show()
+---+
|  c|
+---+
|  3|
+---+相關用法
- Python PySpark SQL Functions countDistinct方法用法及代碼示例
- Python PySpark SQL Functions count方法用法及代碼示例
- Python PySpark SQL Functions concat方法用法及代碼示例
- Python PySpark SQL Functions concat_ws方法用法及代碼示例
- Python PySpark SQL Functions col方法用法及代碼示例
- Python PySpark SQL Functions collect_list方法用法及代碼示例
- Python PySpark SQL Functions collect_set方法用法及代碼示例
- 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 | count_distinct method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
