Condividi tramite


Classe DataFrameNaFunctions

Funzionalità per l'uso di dati mancanti in un dataframe.

Supporta Spark Connect

Sintassi

DataFrame.na

Methods

metodo Descrizione
drop(how, thresh, subset) Restituisce un nuovo dataframe che omette righe con valori Null o NaN.
fill(value, subset) Restituisce un nuovo dataframe con valori Null sostituiti dal valore specificato.
replace(to_replace, value, subset) Restituisce un nuovo dataframe sostituendo un valore con un altro valore.

Examples

Eliminare righe con valori Null

from pyspark.sql import Row

df = spark.createDataFrame([
    Row(age=10, height=80.0, name="Alice"),
    Row(age=5, height=None, name="Bob"),
    Row(age=None, height=None, name="Tom"),
])

df.na.drop().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 10|  80.0|Alice|
+---+------+-----+

Compilare i valori Null

df = spark.createDataFrame([
    (10, 80.5, "Alice"),
    (5, None, "Bob"),
    (None, None, "Tom")],
    schema=["age", "height", "name"])

df.na.fill({'age': 50, 'name': 'unknown'}).show()
+---+------+-------+
|age|height|   name|
+---+------+-------+
| 10|  80.5|  Alice|
|  5|  NULL|    Bob|
| 50|  NULL|unknown|
+---+------+-------+

Sostituire i valori

df = spark.createDataFrame([
    (10, 80, "Alice"),
    (5, None, "Bob"),
    (None, 10, "Tom")],
    schema=["age", "height", "name"])

df.na.replace(['Alice', 'Bob'], ['A', 'B'], 'name').show()
+----+------+----+
| age|height|name|
+----+------+----+
|  10|    80|   A|
|   5|  NULL|   B|
|NULL|    10| Tom|
+----+------+----+