【问题标题】:I want to know how to make a row through the pyspark dataframe fiilter我想知道如何通过 pyspark 数据框过滤器排成一行
【发布时间】:2020-12-10 12:27:30
【问题描述】:
我想知道如何通过 pyspark 数据框过滤器进行一行。
word ㅣ count ㅣ rank
'hello' ㅣ 10 ㅣ 1
'hi' ㅣ 5 ㅣ 2
'python'ㅣ 3 ㅣ 3
'spark' ㅣ 2 ㅣ 4
'java' ㅣ 1 ㅣ 5
结果
word ㅣ count ㅣ rank
'hello' ㅣ 10 ㅣ 1
'hi' ㅣ 5 ㅣ 2
'python'ㅣ 3 ㅣ 3
'etc' ㅣ 3 ㅣ 4
从排名第 4 位开始,我想通过添加 count 到 etc 组来排行。我该怎么做?
【问题讨论】:
标签:
dataframe
filter
pyspark
sum
【解决方案1】:
按条件分组。
import pyspark.sql.functions as f
df.groupBy(f.when(f.col('rank') < 4, f.col('word')).otherwise(f.lit('\'etc\'')).alias('word')) \
.agg(f.sum('count').alias('count'), f.min('rank').alias('rank')) \
.orderBy('rank').show(10, False)
+--------+-----+----+
|word |count|rank|
+--------+-----+----+
|'hello' |10 |1 |
|'hi' |5 |2 |
|'python'|3 |3 |
|'etc' |3 |4 |
+--------+-----+----+