Apache spark 如何将管道分隔列拆分为多行?
我有一个包含以下内容的数据框:Apache spark 如何将管道分隔列拆分为多行?,apache-spark,apache-spark-sql,Apache Spark,Apache Spark Sql,我有一个包含以下内容的数据框: movieId / movieName / genre 1 example1 action|thriller|romance 2 example2 fantastic|action movieId / movieName / genre 1 example1 action 1 example1 thriller 1 example1 romance 2
movieId / movieName / genre
1 example1 action|thriller|romance
2 example2 fantastic|action
movieId / movieName / genre
1 example1 action
1 example1 thriller
1 example1 romance
2 example2 fantastic
2 example2 action
我想获得第二个数据帧(来自第一个数据帧),其中包含以下内容:
movieId / movieName / genre
1 example1 action|thriller|romance
2 example2 fantastic|action
movieId / movieName / genre
1 example1 action
1 example1 thriller
1 example1 romance
2 example2 fantastic
2 example2 action
我该怎么做呢?我会使用
split
标准函数
scala> movies.show(truncate = false)
+-------+---------+-----------------------+
|movieId|movieName|genre |
+-------+---------+-----------------------+
|1 |example1 |action|thriller|romance|
|2 |example2 |fantastic|action |
+-------+---------+-----------------------+
scala> movies.withColumn("genre", explode(split($"genre", "[|]"))).show
+-------+---------+---------+
|movieId|movieName| genre|
+-------+---------+---------+
| 1| example1| action|
| 1| example1| thriller|
| 1| example1| romance|
| 2| example2|fantastic|
| 2| example2| action|
+-------+---------+---------+
// You can use \\| for split instead
scala> movies.withColumn("genre", explode(split($"genre", "\\|"))).show
+-------+---------+---------+
|movieId|movieName| genre|
+-------+---------+---------+
| 1| example1| action|
| 1| example1| thriller|
| 1| example1| romance|
| 2| example2|fantastic|
| 2| example2| action|
+-------+---------+---------+
p、 您可以使用Dataset.flatMap来实现相同的结果,我相信Scala开发者会更喜欢这个结果。使用RDD
val df = Seq((1,"example1","action|thriller|romance"),(2,"example2","fantastic|action")).toDF("Id","name","genre")
df.rdd.flatMap( x=>{ val p = x.getAs[String]("genre"); for { a <- p.split("[|]") } yield (x(0),x(1),a)} ).foreach(println)
要转换回DF
val rdd1 = df.rdd.flatMap( x=>{ val p = x.getAs[String]("genre"); for { a <- p.split("[|]") } yield Row(x(0),x(1),a)} )
spark.createDataFrame(rdd1,df.schema.copy(Array(StructField("Id",IntegerType),StructField("name",StringType))).add(StructField("genre2",StringType))).show(false)
val rdd1=df.rdd.flatMap(x=>{val p=x.getAs[String](“流派”);用于{a'@Jacek..你提到了其他答案,但只有一个答案是你的..@stack0114106谢谢。它们似乎同时被删除了。请从答案中删除噪音。@JacekLaskowski如果我们有两个带有|分隔符的列,我们如何拆分。例如,除了类型之外,如果我们还有一个具有多个分隔符的“演员”列,那么我们如何拆分呢名称。@Ahmad想单独问一个问题吗?这样我们就有更多的空间和可视性来讨论您的用例?谢谢。