cast
Convert the column to a different data type.
Syntax
Python
cast(dataType)
Parameters
Parameter | Type | Description |
|---|---|---|
| DataType or str | Target data type |
Returns
Column
Examples
Cast with a string type name:
Python
from pyspark.sql.types import StringType
df = spark.createDataFrame(
[(2, "Alice"), (5, "Bob")], ["age", "name"])
df.select(df.age.cast("string").alias('ages')).collect()
Output
# [Row(ages='2'), Row(ages='5')]
Cast with a DataType instance:
Python
from pyspark.sql.types import StringType
df = spark.createDataFrame(
[(2, "Alice"), (5, "Bob")], ["age", "name"])
df.select(df.age.cast(StringType()).alias('ages')).collect()
Output
# [Row(ages='2'), Row(ages='5')]