Scala 根据列中的值复制Spark dataframe中的行
我想根据给定列的值复制行。例如,我得到了这个数据帧:Scala 根据列中的值复制Spark dataframe中的行,scala,apache-spark,dataframe,Scala,Apache Spark,Dataframe,我想根据给定列的值复制行。例如,我得到了这个数据帧: +-----+ |count| +-----+ | 3| | 1| | 4| +-----+ 我想得到: +-----+ |count| +-----+ | 3| | 3| | 3| | 1| | 4| | 4| | 4| | 4| +-----+ 据介绍,我尝试使用with column方法 但是,$“count”是一个列名,不能用于在上述表达式中表示其值 (我也试过使用
+-----+
|count|
+-----+
| 3|
| 1|
| 4|
+-----+
我想得到:
+-----+
|count|
+-----+
| 3|
| 3|
| 3|
| 1|
| 4|
| 4|
| 4|
| 4|
+-----+
据介绍,我尝试使用with column
方法
但是,$“count”
是一个列名
,不能用于在上述表达式中表示其值
(我也试过使用explode(Array.fill($“count”){1})
,但这里也有同样的问题。)
我需要改变什么?有更干净的方法吗?您可以使用以下功能:
import org.apache.spark.sql.functions.{array_repeat, explode}
val df = Seq(1, 2, 3).toDF
df.select(explode(array_repeat($"value", $"value"))).show()
+---+
|上校|
+---+
| 1|
| 2|
| 2|
| 3|
| 3|
| 3|
+---+
您可以使用以下功能:
import org.apache.spark.sql.functions.{array_repeat, explode}
val df = Seq(1, 2, 3).toDF
df.select(explode(array_repeat($"value", $"value"))).show()
+---+
|上校|
+---+
| 1|
| 2|
| 2|
| 3|
| 3|
| 3|
+---+
阵列\u repeat
从2.4版开始提供。如果需要较低版本的解决方案,可以使用udf()或rdd。对于Rdd,请查看此项
import scala.collection.mutable._
val df = Seq(3,1,4).toDF("count")
val rdd1 = df.rdd.flatMap( x=> { val y = x.getAs[Int]("count"); for ( p <- 0 until y ) yield Row(y) } )
spark.createDataFrame(rdd1,df.schema).show(false)
单独使用df()
对于udf()
val df = Seq(3,1,4).toDF("count")
def array_repeat(x:Int):Array[Int]={
val y = for ( p <- 0 until x )yield x
y.toArray
}
val udf_array_repeat = udf (array_repeat(_:Int):Array[Int] )
df.withColumn("count2", explode(udf_array_repeat('count))).select("count2").show(false)
val df=Seq(3,1,4).toDF(“计数”)
def array_repeat(x:Int):数组[Int]={
val y=for(parray_repeat
从2.4版开始提供。如果您需要较低版本的解决方案,可以使用udf()或rdd。对于rdd,请查看此项
import scala.collection.mutable._
val df = Seq(3,1,4).toDF("count")
val rdd1 = df.rdd.flatMap( x=> { val y = x.getAs[Int]("count"); for ( p <- 0 until y ) yield Row(y) } )
spark.createDataFrame(rdd1,df.schema).show(false)
单独使用df()
对于udf()
val df = Seq(3,1,4).toDF("count")
def array_repeat(x:Int):Array[Int]={
val y = for ( p <- 0 until x )yield x
y.toArray
}
val udf_array_repeat = udf (array_repeat(_:Int):Array[Int] )
df.withColumn("count2", explode(udf_array_repeat('count))).select("count2").show(false)
val df=Seq(3,1,4).toDF(“计数”)
def array_repeat(x:Int):数组[Int]={
val y=for(p)使用flatMap如何?使用flatMap如何?这似乎仅在重复次数为int但不为bigint时有效。这似乎仅在重复次数为int但不为bigint时有效。。