pyspark.sql.functions.reverse#

pyspark.sql.functions.reverse(col)[source]#

Collection function: returns a reversed string or an array with elements in reverse order.

New in version 1.5.0.

Changed in version 3.4.0: Supports Spark Connect.

Parameters
colColumn or str

The name of the column or an expression that represents the element to be reversed.

Returns
Column

A new column that contains a reversed string or an array with elements in reverse order.

Examples

Example 1: Reverse a string

>>> import pyspark.sql.functions as sf
>>> df = spark.createDataFrame([('Spark SQL',)], ['data'])
>>> df.select(sf.reverse(df.data)).show()
+-------------+
|reverse(data)|
+-------------+
|    LQS krapS|
+-------------+

Example 2: Reverse an array

>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame([([2, 1, 3],) ,([1],) ,([],)], ['data'])
>>> df.select(sf.reverse(df.data)).show()
+-------------+
|reverse(data)|
+-------------+
|    [3, 1, 2]|
|          [1]|
|           []|
+-------------+