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

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值