agg内计数函数的pyspark-奇怪行为 [英] pyspark-strange behavior of count function inside agg

查看:32
本文介绍了agg内计数函数的pyspark-奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 spark 2.4.0我在使用计数函数聚合时观察到一个奇怪的行为.

I am using spark 2.4.0 I am observing a strange behavior while using count function to aggregate.

from pyspark.sql import functions as F
tst=sqlContext.createDataFrame([(1,2),(1,5),(2,None),(2,3),(3,None),(3,None)],schema=['col1','col2'])
tst.show()
+----+----+
|col1|col2|
+----+----+
|   1|   2|
|   1|   5|
|   2|null|
|   2|   3|
|   3|null|
|   3|null|
+----+----+

tst.groupby('col1').agg(F.count('col2')).show()
+----+-----------+
|col1|count(col2)|
+----+-----------+
|   1|          2|
|   3|          0|
|   2|          1|
+----+-----------+

这里可以看到没有计算空值.我搜索了文档,但没有提到函数计数不计算空值.更让我吃惊的是这个

Here you can see that the null values are not counted. I searched for the docus, but no where it is mentioned that the function count does not count null values. More surprising for me is this

tst.groupby('col1').agg(F.count(F.col('col2').isNull())).show()
+----+---------------------+
|col1|count((col2 IS NULL))|
+----+---------------------+
|   1|                    2|
|   3|                    2|
|   2|                    2|
+----+---------------------+

这里我完全糊涂了.当我使用 isNull() 时,它不应该只计算空值吗?为什么要计算所有值?

Here I am totally confused. When I use isNull(), shouldn't it count only null values? Why is it counting all the values?

我有什么遗漏吗?

推荐答案

在这两种情况下,您看到的结果都是预期的.

In both cases the results that you see are the expected ones.

关于第一个例子:检查 Scala 计数来源 count(*)count('col2'):

Concerning the first example: Checking the Scala source of count there is a subtle difference between count(*) and count('col2'):

FUNC(*) - 返回检索到的总行数,包括包含空值的行.
FUNC(expr[, expr...]) - 返回所提供的表达式都为非空的行数.

FUNC(*) - Returns the total number of retrieved rows, including rows containing null.
FUNC(expr[, expr...]) - Returns the number of rows for which the supplied expression(s) are all non-null.

这解释了为什么 null 条目不被计算在内.

This explains why the null entries are not counted.

如果你把代码改成

tst.groupby('col1').agg(F.count('*')).show()

你得到

+----+--------+
|col1|count(1)|
+----+--------+
|   1|       2|
|   3|       2|
|   2|       2|
+----+--------+


关于第二部分:表达式 F.col('col2').isNull() 返回一个布尔值.不管这个布尔值的实际值是多少,该行都会被计算在内,因此你会看到一个 2.


About the second part: the expression F.col('col2').isNull() returns a boolean value. No matter what the actual value of this boolean is, the row is counted and therefore you see a 2.

这篇关于agg内计数函数的pyspark-奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆