transform
Returns an array of elements after applying a transformation to each element in the input array. Supports Spark Connect.
For the corresponding Databricks SQL function, see transform function.
Syntax
Python
from pyspark.databricks.sql import functions as dbf
dbf.transform(col=<col>, f=<f>)
Parameters
Parameter | Type | Description |
|---|---|---|
|
| Name of column or expression. |
|
| A function that is applied to each element of the input array. Can take one of the following forms: Unary |
Returns
pyspark.sql.Column: a new array of transformed elements.
Examples
Example 1: Transform array elements with a simple function
Python
from pyspark.databricks.sql import functions as dbf
df = spark.createDataFrame([(1, [1, 2, 3, 4])], ("key", "values"))
df.select(dbf.transform("values", lambda x: x * 2).alias("doubled")).show()
Output
+------------+
| doubled|
+------------+
|[2, 4, 6, 8]|
+------------+
Example 2: Transform array elements using index
Python
from pyspark.databricks.sql import functions as dbf
df = spark.createDataFrame([(1, [1, 2, 3, 4])], ("key", "values"))
def alternate(x, i):
return dbf.when(i % 2 == 0, x).otherwise(-x)
df.select(dbf.transform("values", alternate).alias("alternated")).show()
Output
+--------------+
| alternated|
+--------------+
|[1, -2, 3, -4]|
+--------------+