pyspark数据类型转换-withColumn,select,selectExpr,sql四种方式

pyspark数据类型转换-withColumn,select,selectExpr,sql四种方式,第1张

pyspark数据类型转换-withColumn,select,selectExpr,sql四种方式

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5665843.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存