Pular para o conteúdo principal

ordenar_array

Ordena a matriz de entrada em ordem crescente ou decrescente, de acordo com a ordem natural dos elementos da matriz. Os elementos nulos serão colocados no início da matriz retornada em ordem crescente ou no final da matriz retornada em ordem decrescente.

Sintaxe

Python
from pyspark.sql import functions as sf

sf.sort_array(col, asc=True)

Parâmetros

Parâmetro

Tipo

Descrição

col

pyspark.sql.Column ou str

Nome da coluna ou expressão.

asc

booleano, opcional

Se deseja classificar em ordem crescente ou decrescente. Se asc for True (default), a ordenação será em ordem crescente. Se falso, então em ordem decrescente.

Devoluções

pyspark.sql.ColumnMatriz ordenada.

Exemplos

Exemplo 1 : Ordenando um array em ordem crescente

Python
import pyspark.sql.functions as sf
df = spark.createDataFrame([([2, 1, None, 3],)], ['data'])
df.select(sf.sort_array(df.data)).show()
Output
+----------------------+
|sort_array(data, true)|
+----------------------+
| [NULL, 1, 2, 3]|
+----------------------+

Exemplo 2 : Ordenando um array em ordem decrescente

Python
import pyspark.sql.functions as sf
df = spark.createDataFrame([([2, 1, None, 3],)], ['data'])
df.select(sf.sort_array(df.data, asc=False)).show()
Output
+-----------------------+
|sort_array(data, false)|
+-----------------------+
| [3, 2, 1, NULL]|
+-----------------------+

Exemplo 3 : Ordenando uma matriz com um único elemento

Python
import pyspark.sql.functions as sf
df = spark.createDataFrame([([1],)], ['data'])
df.select(sf.sort_array(df.data)).show()
Output
+----------------------+
|sort_array(data, true)|
+----------------------+
| [1]|
+----------------------+

Exemplo 4 : Ordenando uma matriz vazia

Python
from pyspark.sql import functions as sf
from pyspark.sql.types import ArrayType, StringType, StructField, StructType
schema = StructType([StructField("data", ArrayType(StringType()), True)])
df = spark.createDataFrame([([],)], schema=schema)
df.select(sf.sort_array(df.data)).show()
Output
+----------------------+
|sort_array(data, true)|
+----------------------+
| []|
+----------------------+

Exemplo 5 : Ordenando uma matriz com valores nulos

Python
from pyspark.sql import functions as sf
from pyspark.sql.types import ArrayType, IntegerType, StructType, StructField
schema = StructType([StructField("data", ArrayType(IntegerType()), True)])
df = spark.createDataFrame([([None, None, None],)], schema=schema)
df.select(sf.sort_array(df.data)).show()
Output
+----------------------+
|sort_array(data, true)|
+----------------------+
| [NULL, NULL, NULL]|
+----------------------+