Piotr Reszke
Piotr Reszke

Reputation: 1596

Modify Spark DataFrame structure

Lets say that I have a Spark DataFrame with the following columns:

| header1 | location | precision | header2 | velocity | data |

(This df also contains some data)

Now I would like to transform the df into a new structure with 2 columns, each having complex fields - something like that:

|          gps                   |         velocity          |
| header1 | location | precision | header2 | velocity | data |

The best if I could just call a method:

df1 = createStructure(df, "gps", ["header1", "gps", "precision"])
df2 = createStructure(df1, "velocity", ["header2", "velocity", "data"])

I was experimenting with "withColumn" but no luck there

Upvotes: 0

Views: 77

Answers (1)

C.S.Reddy Gadipally
C.S.Reddy Gadipally

Reputation: 1758

Try this.

scala> import org.apache.spark.sql.functions._
import org.apache.spark.sql.functions._

scala> val df1 = Seq(("h1-4", "loc4", "prec4", "h2-4", "vel4", "d4"), ("h1-5", "loc5", "prec5", "h2-5", "vel5", "d5")).toDF("header1", "location", "precision", "header2", "velocity", "data")
df1: org.apache.spark.sql.DataFrame = [header1: string, location: string ... 4 more fields]

scala> df1.show(false)
+-------+--------+---------+-------+--------+----+
|header1|location|precision|header2|velocity|data|
+-------+--------+---------+-------+--------+----+
|h1-4   |loc4    |prec4    |h2-4   |vel4    |d4  |
|h1-5   |loc5    |prec5    |h2-5   |vel5    |d5  |
+-------+--------+---------+-------+--------+----+


scala> val outputDF = df1.withColumn("gps", struct($"header1", $"location", $"precision")).withColumn("velocity", struct($"header2", $"velocity", $"data")).select("gps", "velocity")
outputDF: org.apache.spark.sql.DataFrame = [gps: struct<header1: string, location: string ... 1 more field>, velocity: struct<header2: string, velocity: string ... 1 more field>]

scala> outputDF.printSchema
root
|-- gps: struct (nullable = false)
|    |-- header1: string (nullable = true)
|    |-- location: string (nullable = true)
|    |-- precision: string (nullable = true)
|-- velocity: struct (nullable = false)
|    |-- header2: string (nullable = true)
|    |-- velocity: string (nullable = true)
|    |-- data: string (nullable = true)


scala> outputDF.show(false)
+-------------------+----------------+
|gps                |velocity        |
+-------------------+----------------+
|[h1-4, loc4, prec4]|[h2-4, vel4, d4]|
|[h1-5, loc5, prec5]|[h2-5, vel5, d5]|
+-------------------+----------------+

Upvotes: 1

Related Questions