Aller au contenu principal

array_size

Renvoie le nombre total d'éléments dans le tableau. La fonction renvoie null pour une entrée nulle.

Syntaxe

Python
from pyspark.sql import functions as sf

sf.array_size(col)

parameter

parameter

Type

Description

col

pyspark.sql.Column ou str

Le nom de la colonne ou une expression qui représente le tableau.

parameter

Type

Description

col

pyspark.sql.Column ou str

Le nom de la colonne ou une expression qui représente le tableau.

Renvoie

pyspark.sql.Column: Une nouvelle colonne qui contient la taille de chaque tableau.

Exemples

Exemple 1 : Utilisation de base avec un tableau d'entiers

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

Exemple 2 : utilisation avec un tableau de chaînes.

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(['apple', 'banana', 'cherry'],)], ['data'])
df.select(sf.array_size(df.data)).show()
Output
+----------------+
|array_size(data)|
+----------------+
| 3|
+----------------+

Exemple 3 : Utilisation avec un tableau de types mixtes

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(['apple', 1, 'cherry'],)], ['data'])
df.select(sf.array_size(df.data)).show()
Output
+----------------+
|array_size(data)|
+----------------+
| 3|
+----------------+

**Exemple 4** : Utilisation avec un tableau de tableaux

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

Exemple 5 : utilisation avec un tableau vide

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([([],)], schema=schema)
df.select(sf.array_size(df.data)).show()
Output
+----------------+
|array_size(data)|
+----------------+
| 0|
+----------------+