dataframe行变换为列

网友投稿 708 2022-10-02

dataframe行变换为列

dataframe行变换为列

新建一个 ​​dataFrame​​ :

val conf = new SparkConf().setAppName("TTyb").setMaster("local")val sc = new SparkContext(conf)val spark: SQLContext = new SQLContext(sc)import org.apache.spark.sql.functions.explodeimport org.apache.spark.sql.functions.splitimport spark.implicits._val dataFrame = spark.createDataFrame(Seq( (1, "example1", "a|b|c"), (2, "example2", "d|e"))).toDF("id", "name", "content")

需要将 ​​content​​​ 的内容按照 ​​|​​ 分割,得到如下效果:

+---+--------+-------+| id| name|content|+---+--------+-------+| 1|example1| a|| 1|example1| b|| 1|example1| c|| 2|example2| d|| 2|example2| e|+---+--------+-------+

目前有两种方式实现。

方式一

使用 ​​import org.apache.spark.sql.functions​​​ 里面的函数,具体的方式可以看 ​​functions​​ :

import org.apache.spark.sql.functions.{explode,split}import spark.implicits._dataFrame.withColumn("content", explode(split($"content", "[|]"))).show

方式二

使用 ​​udf​​​ ,具体的方式可以看 ​​spark使用udf给dataFrame新增列​​

import org.apache.spark.sql.functions.explodeval stringtoArray =org.apache.spark.sql.functions.udf((content : String) => {content.split('|')})dataFrame.withColumn("content", explode(stringtoArray(dataFrame("content")))).show

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Springboot
下一篇:如何配置小程序业务域名(配置小程序业务域名百度定位)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~