Spark支持融化和dcast

sag*_*sag 4 scala r melt apache-spark spark-dataframe

我们使用melt和dcast来转换宽 - >长 - 长 - >宽格式的数据.有关详细信息,请参阅http://seananderson.ca/2013/10/19/reshape.html.

scala或SparkR都可以.

我已经浏览了这个博客scala函数以及R API.我没有看到做类似工作的功能.

Spark中有任何等效功能吗?如果没有,在Spark中有没有其他方法可以做到这一点?

Neh*_*haM 10

使用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
  }
Run Code Online (Sandbox Code Playgroud)

它做的工作.但我对效率并不十分肯定.

+-----+---+---+----------+------+
| 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|
+-----+---+---+----------+------+
Run Code Online (Sandbox Code Playgroud)

可以用作

melt(df, List("name", "sex"))
Run Code Online (Sandbox Code Playgroud)

结果如下:

+-----+---+--------+----------+
| 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|
+-----+---+--------+----------+
Run Code Online (Sandbox Code Playgroud)

如果有改进的余地,我希望它有用并感谢您的意见.