カウントイフ
列の TRUE 値の数を返します。
構文
Python
from pyspark.sql import functions as sf
sf.count_if(col)
パラメーター
パラメーター | Type | 説明 |
|---|---|---|
|
| 取り組むターゲットカラム。 |
戻り値
pyspark.sql.Column: colのTRUE値の数。
例
例1 :数値列内の偶数の数を数える
Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([("a", 1), ("a", 2), ("a", 3), ("b", 8), ("b", 2)], ["c1", "c2"])
df.select(sf.count_if(sf.col('c2') % 2 == 0)).show()
Output
+------------------------+
|count_if(((c2 % 2) = 0))|
+------------------------+
| 3|
+------------------------+
例2 : 文字列の列が特定の文字で始まる行の数を数える
Python
from pyspark.sql import functions as sf
df = spark.createDataFrame(
[("apple",), ("banana",), ("cherry",), ("apple",), ("banana",)], ["fruit"])
df.select(sf.count_if(sf.col('fruit').startswith('a'))).show()
Output
+------------------------------+
|count_if(startswith(fruit, a))|
+------------------------------+
| 2|
+------------------------------+
例3 : 数値列が特定の値より大きい行の数を数える
Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(1,), (2,), (3,), (4,), (5,)], ["num"])
df.select(sf.count_if(sf.col('num') > 3)).show()
Output
+-------------------+
|count_if((num > 3))|
+-------------------+
| 2|
+-------------------+
例4 : ブール列がTrueである行の数を数える
Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(True,), (False,), (True,), (False,), (True,)], ["b"])
df.select(sf.count('b'), sf.count_if('b')).show()
Output
+--------+-----------+
|count(b)|count_if(b)|
+--------+-----------+
| 5| 3|
+--------+-----------+