首页 > 解决方案 > Pyspapk 计算符合条件的出现次数

问题描述

在 pyspark 中,我有每个国家/地区的 df 数据,我想计算值小于 100 时的出现次数。以及值小于 1000 时的出现次数。

Country  value 
Us         10
Us         150
Us         102
Us         15000
Ru         13
Ru         175
Ru         122
Ind        14000
Ind        2000
Ind        780
Ind        900
Ind        55

Us 有 1 个出现在 100 以下。3 个出现在 1000 以下。Ru 有 1 个出现在 100 以下,3 个出现在 1000 以下等等。

我如何获得这些信息?有没有办法按国家分组并计算条件满足的出现次数?如果是这样,是否可以区分每个条件。像一次100,另一个1000?

标签: pysparkgroup-bycountconditional-statements

解决方案


使用 window 进行分区,Country您可以有条件地对计数求和。

from pyspark.sql import Window
w = Window.partitionBy('Country')

df.withColumn('100', sum(when(col('value') <= 100, 1)).over(w)) \
  .withColumn('1000', sum(when(col('value') <= 1000, 1)).over(w)) \
  .show()

+-------+-----+---+----+
|Country|value|100|1000|
+-------+-----+---+----+
|     Ru|   13|  1|   3|
|     Ru|  175|  1|   3|
|     Ru|  122|  1|   3|
|     Us|   10|  1|   3|
|     Us|  150|  1|   3|
|     Us|  102|  1|   3|
|     Us|15000|  1|   3|
|    Ind|14000|  1|   3|
|    Ind| 2000|  1|   3|
|    Ind|  780|  1|   3|
|    Ind|  900|  1|   3|
|    Ind|   55|  1|   3|
+-------+-----+---+----+

推荐阅读