Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PySpark equivalent of function "typedLit" from Scala API

We have a function typedLit in Scala API for Spark to add the Array or Map as column value.

import org.apache.spark.sql.functions.typedLit
val df1 = Seq((1, 0), (2, 3)).toDF("a", "b")

df1.withColumn("seq", typedLit(Seq(1,2,3)))
    .show(truncate=false)

+---+---+---------+
|a  |b  |seq      |
+---+---+---------+
|1  |0  |[1, 2, 3]|
|2  |3  |[1, 2, 3]|
+---+---+---------+

I couldn't find the equivalent in PySpark. How can we create a column in PySpark with Array as a column value?

like image 359
Neeraj Bhadani Avatar asked May 31 '20 10:05

Neeraj Bhadani


People also ask

Can I use Scala in PySpark?

Well, there is: we can write our ETLs in Pyspark and run Scala code directly from it if necessary. First, let's build a toy Scala project we shall use for demonstration. Now we can populate it with some tenants. We are finally in position to build a jar from our toy project.

What is Spark typedLit?

The Spark SQL functions lit() and typedLit() add the new constant column to the DataFrame by assigning the literal or a constant value. Both lit() and typedLit() functions are available in the Spark by importing "org. apache.

Is Spark Scala faster than PySpark?

This thread has a dated performance comparison. “Regular” Scala code can run 10-20x faster than “regular” Python code, but that PySpark isn't executed liked like regular Python code, so this performance comparison isn't relevant. PySpark is converted to Spark SQL and then executed on a JVM cluster.


1 Answers

There isn't an equivalent function in pyspark yet, but you can have an array column as shown below:

from pyspark.sql.functions import array, lit
df = sc.parallelize([[1,2], [3,4]]).toDF(['a', 'b'])
df.withColumn('seq', array([lit(i) for i in [1,2,3]])).show()

Output:

+---+---+---------+                                                             
|  a|  b|      seq|
+---+---+---------+
|  1|  2|[1, 2, 3]|
|  3|  4|[1, 2, 3]|
+---+---+---------+
like image 99
Ani Menon Avatar answered Sep 30 '22 05:09

Ani Menon