withColumnRenamed

Retourne un nouveau DataFrame en renommant une colonne existante. Il s’agit d’un no-op si le schéma ne contient pas le nom de colonne donné.

Syntaxe

withColumnRenamed(existing: str, new: str)

Paramètres

Paramètre Type Description
existing str Nom de la colonne existante à renommer.
new str Nouveau nom à attribuer à la colonne.

Retours

DataFrame: nouveau DataFrame avec une colonne renommée.

Exemples

df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])

df.withColumnRenamed("age", "age2").show()
# +----+-----+
# |age2| name|
# +----+-----+
# |   2|Alice|
# |   5|  Bob|
# +----+-----+

df.withColumnRenamed("non_existing", "new_name").show()
# +---+-----+
# |age| name|
# +---+-----+
# |  2|Alice|
# |  5|  Bob|
# +---+-----+

df.withColumnRenamed("age", "age2").withColumnRenamed("name", "name2").show()
# +----+-----+
# |age2|name2|
# +----+-----+
# |   2|Alice|
# |   5|  Bob|
# +----+-----+