我们使用melt和dcast将数据从宽->长和长->宽格式转换。参考http://seananderson.ca/2013/10/19/reshape.html了解更多详细信息。
scala或SparkR都可以。
我已经浏览了这个博客和scala函数以及R API。我看不出有类似功能。
Spark中有等效的功能吗?如果没有,在Spark中还有其他方法吗?
在Spark中使用Pivot对数据进行整形支持使用pivot
进行整形。我知道melt
大致是枢轴的反方向,也称为unpivot
。我对Spark
还比较陌生。据我所知,我尝试实施熔化操作。
def melt(df: DataFrame, columns: List[String]): DataFrame ={
val restOfTheColumns = df.columns.filterNot(columns.contains(_))
val baseDF = df.select(columns.head, columns.tail: _*)
val newStructure =StructType(baseDF.schema.fields ++ List(StructField("variable", StringType, true), StructField("value", StringType, true)))
var newdf = sqlContext.createDataFrame(sqlContext.sparkContext.emptyRDD[Row], newStructure)
for(variableCol <- restOfTheColumns){
val colValues = df.select(variableCol).map(r=> r(0).toString)
val colRdd=baseDF.rdd.zip(colValues).map(tuple => Row.fromSeq(tuple._1.toSeq.:+(variableCol).:+(tuple._2.toString)))
var colDF =sqlContext.createDataFrame(colRdd, newStructure)
newdf =newdf.unionAll(colDF)
}
newdf
}
它完成了工作。但我对效率不是很确定。
+-----+---+---+----------+------+
| name|sex|age| street|weight|
+-----+---+---+----------+------+
|Alice| f| 34| somewhere| 70|
| Bob| m| 63| nowhere| -70|
|Alice| f|612|nextstreet| 23|
| Bob| m|612| moon| 8|
+-----+---+---+----------+------+
可用作
melt(df, List("name", "sex"))
结果如下:
+-----+---+--------+----------+
| name|sex|variable| value|
+-----+---+--------+----------+
|Alice| f| age| 34|
| Bob| m| age| 63|
|Alice| f| age| 612|
| Bob| m| age| 612|
|Alice| f| street| somewhere|
| Bob| m| street| nowhere|
|Alice| f| street|nextstreet|
| Bob| m| street| moon|
|Alice| f| weight| 70|
| Bob| m| weight| -70|
|Alice| f| weight| 23|
| Bob| m| weight| 8|
+-----+---+--------+----------+
我希望它是有用的,如果还有改进的空间,我感谢你的评论。
这里有一个spark.ml.Transformer
,它只使用数据集操作(没有RDD内容)
case class Melt(meltColumns: String*) extends Transformer{
override def transform(in: Dataset[_]): DataFrame = {
val nonMeltColumns = in.columns.filterNot{ meltColumns.contains }
val newDS = in
.select(nonMeltColumns.head,meltColumns:_*)
.withColumn("variable", functions.lit(nonMeltColumns.head))
.withColumnRenamed(nonMeltColumns.head,"value")
nonMeltColumns.tail
.foldLeft(newDS){ case (acc,col) =>
in
.select(col,meltColumns:_*)
.withColumn("variable", functions.lit(col))
.withColumnRenamed(col,"value")
.union(acc)
}
.select(meltColumns.head,meltColumns.tail ++ List("variable","value") : _*)
}
override def copy(extra: ParamMap): Transformer = defaultCopy(extra)
@DeveloperApi
override def transformSchema(schema: StructType): StructType = ???
override val uid: String = Identifiable.randomUID("Melt")
}
这是一个使用的测试
"spark" should "melt a dataset" in {
import spark.implicits._
val schema = StructType(
List(StructField("Melt1",StringType),StructField("Melt2",StringType)) ++
Range(3,10).map{ i => StructField("name_"+i,DoubleType)}.toList)
val ds = Range(1,11)
.map{ i => Row("a" :: "b" :: Range(3,10).map{ j => Math.random() }.toList :_ *)}
.|>{ rows => spark.sparkContext.parallelize(rows) }
.|>{ rdd => spark.createDataFrame(rdd,schema) }
val newDF = ds.transform{ df =>
Melt("Melt1","Melt2").transform(df) }
assert(newDF.count() === 70)
}
.||是scalaZ管道运算符
Spark DataFrame具有explode
方法,该方法提供R melt
功能。Spark 1.6.1中的工作示例:
// input df has columns (anyDim, n1, n2)
case class MNV(measureName: String, measureValue: Integer);
val dfExploded = df.explode(col("n1"), col("n2")) {
case Row(n1: Int, n2: Int) =>
Array(MNV("n1", n1), MNV("n2", n2))
}
// dfExploded has columns (anyDim, n1, n2, measureName, measureValue)