pyspark - 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?
解决方案
使用 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|
+-------+-----+---+----+
推荐阅读
- java - 邻接矩阵生成器
- python - 在 aws lambda 上运行 python tika
- ios - 发布方法在post方法中不加参数
- r - R闪亮:模块中的insertUI和observeEvent
- c - 如何解释野牛中的“移位/减少”冲突
- arrays - 如何查找数组是否包含特定数组?
- reactjs - 当我使用 axios 时,我调用什么链接到 Amazon s3
- firebase - 有没有办法将画布绘图保存到firebase而不是将其转换为图像
- java - 堆栈跟踪中的 NoSuchElementException,尝试了社区中的其他一些解决方案仍然没有帮助
- android - 如何修复 [未处理的承诺拒绝:错误:位置提供程序不可用。确保已启用位置服务。]