Spark DataFrame pivot()实现分组、透视、求和

问题:

        对A列和B列进行分组,然后在C列上进行透视操作并对D列数据进行求和

实现功能如下:

实现方式

      Spark中语法为:df.groupBy(“A”, “B”).pivot(“C”).sum(“D”),显然这种语法格式非常直观,但这其中也有个值得注意的地方:为取得更好的性能,需要明确指定透视列对应的不同值,例如如果C列有两个不同的值(small 和 large),则性能更优的版本语法为: df.groupBy(“A”, “B”).pivot(“C”, Seq(“small”, “large”)).sum(“D”)。当然,这里给出的是Scala语言实现,使用Java语言和Python语言实现的话方法也是类似的
数据源:

foo     one     small   1
foo     one     large   2
foo     one     large   2
foo     two     small   3
foo     two     small   3
bar     one     large   4
bar     one     small   5
bar     two     small   6
bar     two     large   7

实现代码:

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{StructField, _}

object TestDataFrames {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession
      .builder()
      .appName("Spark SQL basic example")
      .config("spark.some.config.option", "some-value")
      .master("local[2]")
      .getOrCreate()

    val pivotRDD = spark.sparkContext.textFile("/Users/xx/Downloads/tmp/spark/input/pivot.txt")
    val schema = StructType(
      List(
        StructField("A", StringType, true),
        StructField("B", StringType, true),
        StructField("C", StringType, true),
        StructField("D", IntegerType, true)
      )
    )

    val rowRDD = pivotRDD
      .map(_.split("\t"))
      .map(attributes => Row(attributes(0), attributes(1), attributes(2), attributes(3).toInt))
    val peopleDF = spark.createDataFrame(rowRDD, schema)
    peopleDF.createOrReplaceTempView("pivot")

    val results = spark.sql("SELECT * FROM pivot")
    results.show()
    results.groupBy("A", "B").pivot("C").sum("D").show()
  }

}

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值