![](/img/trans.png)
[英]How to perform basic statistics on a csv file to explore my numeric and non-numeric variables with Spark Scala?
[英]Pivot non-numeric table in Spark Scala
是否可以在Spark Scala中旋转具有非数字值的表? 我已经审查了以下两个Stack问题。
按照“何时列出案例”问题中的步骤进行操作,我可以转换数据,以便每个数据类型都是一列,但是每个实体-数据类型组合都有一行。
id tag value
1 US foo
1 UK bar
1 CA baz
2 US hoo
2 UK hah
2 CA wah
id US UK CA
1 foo
1 bar
1 baz
2 hoo
2 hah
3 wah
是否有一个“第一个非空”函数可以将每个实体的多行折叠为一个?
id US UK CA
1 foo bar baz
2 hoo hah wah
这是一个完整的Scala类,它创建一个示例数据框,然后对其进行透视。 它是专门针对此问题的,因此我不知道它通常会有多大用处。 还没有经过广泛的测试,所以买家要当心。
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{Column, DataFrame, Row, SQLContext}
import org.apache.spark.sql.functions.{lit, when}
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}
object DemoPivot {
def main(args: Array[String]) = {
def pivotColumn(df: DataFrame)(t: String): Column = {
val col = when(df("tag") <=> lit(t), df("value"))
col.alias(t)
}
def pivotFrame(sqlContext: SQLContext, df: DataFrame): DataFrame = {
val tags = df.select("tag").distinct.map(r => r.getString(0)).collect.toList
df.select(df("id") :: tags.map(pivotColumn(df)): _*)
}
def aggregateRows(value: Seq[Option[Any]], agg: Seq[Option[Any]]): Seq[Option[Any]] = {
for (i <- 0 until Math.max(value.size, agg.size)) yield i match {
case x if x > value.size => agg(x)
case y if y > agg.size => value(y)
case z if value(z).isEmpty => agg(z)
case a => value(a)
}
}
def collapseRows(sqlContext: SQLContext, df: DataFrame): DataFrame = {
// RDDs cannot have null elements, so pack into Options and unpack before returning
val rdd = df.map(row => (Some(row(0)), row.toSeq.tail.map(element => if (element == null) None else Some(element))))
val agg = rdd.reduceByKey(aggregateRows)
val aggRdd = agg.map{ case (key, list) => Row.fromSeq((key.get) :: (list.map(element => if (element.isDefined) element.get else null)).toList) }
sqlContext.createDataFrame(aggRdd, df.schema)
}
val conf = new SparkConf().setAppName("Simple Pivot Demo")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val data = List((1, "US", "foo"), (1, "UK", "bar"), (1, "CA", "baz"),
(2, "US", "hoo"), (2, "UK", "hah"), (2, "CA", "wah"))
val rows = data.map(d => Row.fromSeq(d.productIterator.toList))
val fields = Array(StructField("id", IntegerType, nullable = false),
StructField("tag", StringType, nullable = false),
StructField("value", StringType, nullable = false))
val df = sqlContext.createDataFrame(sc.parallelize(rows), StructType(fields))
df.show()
val pivoted = pivotFrame(sqlContext, df)
pivoted.show()
val collapsed = collapseRows(sqlContext, pivoted)
collapsed.show()
}
}
您可以考虑使用aggregate
方法(或aggregateByKey
)。 您只需要编写适当的函数即可在每个位置获取非null元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.