Apache Spark how to add new column from list / array to Spark dataframe

I am using Apache Spark 2.0 Dataframe / Dataset API I want to add a new column to my dataframe from a list of values. My list has the same number of values ​​as this frame.

val list = List(4,5,10,7,2)
val df   = List("a","b","c","d","e").toDF("row1")

      

I would like to do something like:

val appendedDF = df.withColumn("row2",somefunc(list))
df.show()
// +----+------+
// |row1 |row2 |
// +----+------+
// |a    |4    |
// |b    |5    |
// |c    |10   |
// |d    |7    |
// |e    |2    |
// +----+------+

      

For any ideas I would really like, my dataframe actually contains more columns.

+3


source to share


2 answers


You can do it like this:



import org.apache.spark.sql.Row
import org.apache.spark.sql.types._    

// create rdd from the list
val rdd = sc.parallelize(List(4,5,10,7,2))
// rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[31] at parallelize at <console>:28

// zip the data frame with rdd
val rdd_new = df.rdd.zip(rdd).map(r => Row.fromSeq(r._1.toSeq ++ Seq(r._2)))
// rdd_new: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[33] at map at <console>:32

// create a new data frame from the rdd_new with modified schema
spark.createDataFrame(rdd_new, df.schema.add("new_col", IntegerType)).show
+----+-------+
|row1|new_col|
+----+-------+
|   a|      4|
|   b|      5|
|   c|     10|
|   d|      7|
|   e|      2|
+----+-------+

      

+5


source


Adding for completeness: the fact that the input list

(which exists in driver memory) is the same size as it DataFrame

suggests that this is a small DataFrame to start with, so you might want to consider collect()

- with list

and convert back to DataFrame

:

df.collect()
  .map(_.getAs[String]("row1"))
  .zip(list).toList
  .toDF("row1", "row2")

      



It won't be any faster, but if the data is really small it might be minor and the code is (possibly) clearer.

+4


source







All Articles