PySpark SQL 函數的 count(~)
是一種聚合方法,與 agg(~)
方法結合使用來計算每個組中的項目數。
參數
1.col
| string
或 Column
要執行計數的列。
返回值
新的 PySpark 列。
例子
考慮以下PySpark DataFrame:
df = spark.createDataFrame([['Alex','A'],['Bob','B'],['Cathy','A']], ['name','class'])
df.show()
+-----+-----+
| name|class|
+-----+-----+
| Alex| A|
| Bob| B|
|Cathy| A|
+-----+-----+
計算每組中的項目數
要計算每個 class
組的行數:
import pyspark.sql.functions as F
df.groupBy('class').agg(F.count('class').alias('COUNT')).show()
+-----+-----+
|class|COUNT|
+-----+-----+
| A| 2|
| B| 1|
+-----+-----+
在此,請注意以下事項:
-
我們首先使用
groupBy(~)
按class
列進行分組,然後對於每個組,我們計算有多少行。從技術上講,我們正在計算每個組中class
值的數量 (F.count('class')
),但這相當於隻計算每個組中的行數。 -
我們使用
alias(~)
方法為生成的聚合列分配標簽。請注意,分配的默認標簽是'count'
。
相關用法
- Python PySpark SQL Functions count_distinct方法用法及代碼示例
- Python PySpark SQL Functions countDistinct方法用法及代碼示例
- 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 method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。