0
votes

J'ai une source de données dans deux rangées et plusieurs colonnes, comment transposer en deux colonnes et plusieurs lignes?

J'ai un Spark Dataframe comme ceci: xxx

Comment pouvez-vous pover à xxx

y a-t-il un code simple dans Spark Scala qui peut être utilisé pour la transposition?


1 commentaires

Pourriez-vous partager tout ce que vous avez essayé?


3 Réponses :


0
votes
scala> df.show()
+---+---+---+---+---+---+---+
| f1| f2| f3| f4| f5| f6| f7|
+---+---+---+---+---+---+---+
|  5|  4|  5|  2|  5|  5|  5|
+---+---+---+---+---+---+---+


scala> import org.apache.spark.sql.DataFrame

scala> def transposeUDF(transDF: DataFrame, transBy: Seq[String]): DataFrame = {
     |   val (cols, types) = transDF.dtypes.filter{ case (c, _) => !transBy.contains(c)}.unzip
     |   require(types.distinct.size == 1)      
     | 
     |   val kvs = explode(array(
     |     cols.map(c => struct(lit(c).alias("columns"), col(c).alias("value"))): _*
     |   ))
     | 
     |   val byExprs = transBy.map(col(_))
     | 
     |   transDF
     |     .select(byExprs :+ kvs.alias("_kvs"): _*)
     |     .select(byExprs ++ Seq($"_kvs.columns", $"_kvs.value"): _*)
     | }

scala> val df1 = df.withColumn("tempColumn", lit("1"))

scala> transposeUDF(df1, Seq("tempColumn")).drop("tempColumn").show(false)
+-------+-----+
|columns|value|
+-------+-----+
|f1     |5    |
|f2     |4    |
|f3     |5    |
|f4     |2    |
|f5     |5    |
|f6     |5    |
|f7     |5    |
+-------+-----+

0 commentaires

0
votes
scala> var df =Seq(( 5,  4,  5,  2,  5,  5,  5)).toDF("f1", "f2", "f3", "f4", "f5", "f6", "f7")

scala> df.select(array('*).as("v"), lit(df.columns).as("k")).select('v.getItem(0).as("cust_id"), map_from_arrays('k,'v).as("map")).select(explode('map)).show(false)
+---+-----+
|key|value|
+---+-----+
|f1 |5    |
|f2 |4    |
|f3 |5    |
|f4 |2    |
|f5 |5    |
|f6 |5    |
|f7 |5    |
+---+-----+

0 commentaires

0
votes

J'ai écrit une fonction xxx

il a fonctionné xxx

comme ceci xxx < p> et xxx

très sympa!


0 commentaires