【问题标题】: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   |
    +--------+-----+----+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2019-09-02
      • 1970-01-01
      • 2017-06-06
      • 2019-03-07
      相关资源
      最近更新 更多