使用Scala从Spark中列的一系列值中总结为一个新列 [英] Sum up into a new column from a range of values of a column in Spark using Scala

查看:29
本文介绍了使用Scala从Spark中列的一系列值中总结为一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框

I have a dataframe like below

articles
10
99
101
101
10005
1000001
1000001

我想要输出数据框如下

range              sum
1-100              109
101-10000          202
10001-1000000      10005
1000001-100000000  2000002
...                ...

如何实现这一点.我是 Spark 和 Scala 的新手.

How to achieve this. I am new to spark and scala.

推荐答案

我建议你首先使用 when/otherwise 找到你的值的范围,然后你可以分组通过该 range 并对 articles 执行 sum 聚合:

I suggest that you first find the ranges of your values using when/otherwise then you can group by that range and perform a sum aggregation on articles :

import org.apache.spark.sql.functions._

df.withColumn("range", 
          when($"articles" >  0 and $"articles" <= 100, lit("1-100"))
            .otherwise(
              when($"articles" > 100 and $"articles" <= 10000, lit("101-10000")).otherwise(lit("others"))
            )
         ).groupBy("range").agg(sum($"articles")).orderBy("range").show

// +---------+-------------+
// |    range|sum(articles)|
// +---------+-------------+
// |    1-100|          109|
// |101-10000|          202|
// |   others|      2010007|
// +---------+-------------+

这篇关于使用Scala从Spark中列的一系列值中总结为一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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