pyspark.sql.functions.asc#

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

Returns a sort expression for the target column in ascending order. This function is used in sort and orderBy functions.

New in version 1.3.0.

Changed in version 3.4.0: Supports Spark Connect.

Parameters
colColumn or str

Target column to sort by in the ascending order.

Returns
Column

The column specifying the sort order.

Examples

Example 1: Sort DataFrame by ‘id’ column in ascending order.

>>> from pyspark.sql.functions import asc
>>> df = spark.createDataFrame([(4, 'B'), (3, 'A'), (2, 'C')], ['id', 'value'])
>>> df.sort(asc("id")).show()
+---+-----+
| id|value|
+---+-----+
|  2|    C|
|  3|    A|
|  4|    B|
+---+-----+

Example 2: Use asc in orderBy function to sort the DataFrame.

>>> from pyspark.sql.functions import asc
>>> df = spark.createDataFrame([(4, 'B'), (3, 'A'), (2, 'C')], ['id', 'value'])
>>> df.orderBy(asc("value")).show()
+---+-----+
| id|value|
+---+-----+
|  3|    A|
|  4|    B|
|  2|    C|
+---+-----+

Example 3: Combine asc with desc to sort by multiple columns.

>>> from pyspark.sql.functions import asc, desc
>>> df = spark.createDataFrame([(2, 'A', 4),
...                             (1, 'B', 3),
...                             (3, 'A', 2)], ['id', 'group', 'value'])
>>> df.sort(asc("group"), desc("value")).show()
+---+-----+-----+
| id|group|value|
+---+-----+-----+
|  2|    A|    4|
|  3|    A|    2|
|  1|    B|    3|
+---+-----+-----+

Example 4: Implement asc from column expression.

>>> df = spark.createDataFrame([(4, 'B'), (3, 'A'), (2, 'C')], ['id', 'value'])
>>> df.sort(df.id.asc()).show()
+---+-----+
| id|value|
+---+-----+
|  2|    C|
|  3|    A|
|  4|    B|
+---+-----+