pyspark.sql.functions.asc_nulls_first#

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

Sort Function: Returns a sort expression based on the ascending order of the given column name, and null values return before non-null values.

New in version 2.4.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 order.

Examples

Example 1: Sorting a DataFrame with null values in ascending order

>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame([(1, "Bob"), (0, None), (2, "Alice")], ["age", "name"])
>>> df.sort(sf.asc_nulls_first(df.name)).show()
+---+-----+
|age| name|
+---+-----+
|  0| NULL|
|  2|Alice|
|  1|  Bob|
+---+-----+

Example 2: Sorting a DataFrame with multiple columns, null values in ascending order

>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame(
...   [(1, "Bob", None), (0, None, "Z"), (2, "Alice", "Y")], ["age", "name", "grade"])
>>> df.sort(sf.asc_nulls_first(df.name), sf.asc_nulls_first(df.grade)).show()
+---+-----+-----+
|age| name|grade|
+---+-----+-----+
|  0| NULL|    Z|
|  2|Alice|    Y|
|  1|  Bob| NULL|
+---+-----+-----+

Example 3: Sorting a DataFrame with null values in ascending order using column name string

>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame([(1, "Bob"), (0, None), (2, "Alice")], ["age", "name"])
>>> df.sort(sf.asc_nulls_first("name")).show()
+---+-----+
|age| name|
+---+-----+
|  0| NULL|
|  2|Alice|
|  1|  Bob|
+---+-----+