PySpark - Cast Column Type With Examples

PHOTO EMBED

Tue Oct 04 2022 13:30:11 GMT+0000 (Coordinated Universal Time)

Saved by @thiago3442 #python

from pyspark.sql.types import IntegerType,BooleanType,DateType
# Convert String to Integer Type
df.withColumn("age",df.age.cast(IntegerType()))
df.withColumn("age",df.age.cast('int'))
df.withColumn("age",df.age.cast('integer'))

# Using select
df.select(col("age").cast('int').alias("age"))

#Using selectExpr()
df.selectExpr("cast(age as int) age")

#Using with spark.sql()
spark.sql("SELECT INT(age),BOOLEAN(isGraduated),DATE(jobStartDate) from CastExample")
content_copyCOPY

Cast Column Type With Examples

https://sparkbyexamples.com/pyspark/pyspark-cast-column-type/