pyspark中数据类型转换共有4种方式:withColumn, select, selectExpr,sql

介绍以上方法前,我们要知道dataframe中共有哪些数据类型。每一个类型必须是DataType类的子类,包括

ArrayType, BinaryType, BooleanType, CalendarIntervalType, DateType, HiveStringType, MapType, NullType, NumericType, ObjectType, StringType, StructType, TimestampType

有些类型比如IntegerType, DecimalType, ByteType 等是NumericType的子类

1 withColumn方法

from pyspark.sql.types import IntegerType,StringType,DateType
from pyspark.sql.functions import col
# 转换为Integer类型
df.withColumn("age",df.age.cast(IntegerType()))
df.withColumn("age",df.age.cast('int'))
df.withColumn("age",df.age.cast('integer'))

# 转换为String类型
df.withColumn("age",df.age.cast(StringType()))
df.withColumn("age",df.age.cast('string'))
df.withColumn("age",df.age.cast('String'))

# 以上的df.age可替换为df['age']或col("age")

2 select方法

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

2 selectExpr方法

df3 = df2.selectExpr("cast(age as int) age",
    "cast(isGraduated as string) isGraduated",
    "cast(jobStartDate as string) jobStartDate")

3 sql方法

df=spark.sql("SELECT STRING(age),BOOLEAN(isGraduated),DATE(jobStartDate) from CastExample")

df=spark.sql("select cast(age as string),cast(isGraduated as boolean),cast(jobStartDate as date) ")

注意,不能写cast(isGraduated as bool),只能写bool。

以上各种方法大家可排列组合自由发挥尝试,有好多种写法,可能都可以哦。最后选择一种符合个人习惯的写法即可。

参考文献

PySpark – Cast Column Type With Examples

Spark SQL Data Types with Examples

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐