pyspark 笔记 cast 转换列的类型

1 不借助 pyspark.sql.types

python 复制代码
from pyspark.sql.functions import col

data = [("Alice", "28"), ("Bob", "22"), ("Charlie", "30")]
columns = ["name", "age_str"]
df = spark.createDataFrame(data, columns)
df
#DataFrame[name: string, age_str: string]
#创建一个pyspark的DataFrame



#########################以上是源数据,以下是cast之后的结果############################
df.withColumn('cast_col',col('age_str').cast('int'))
#DataFrame[name: string, age_str: string, cast_col: int]

df.withColumn('cast_col',col('age_str').cast('float'))
#DataFrame[name: string, age_str: string, cast_col: float]

2 借助pysparks.sql.types

python 复制代码
from pyspark.sql.types import *
df.withColumn('cast_col',col('age_str').cast(BooleanType()))
#DataFrame[name: string, age_str: string, cast_col: boolean]

|---------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
| BooleanType | |
| ByteType | 字节数据类型,占用一个字节的存储空间 |
| DateType | datetime.date 的数据类型 |
| DecimalType | 这个类型有两个可选参数,分别是 * precision------最大位数 * scale------小数点右侧位数 |
| DoubleType | |
| FloatType | |
| IntegerType | |
| LongType | |
| NullType | |
| ShortType | |
| StringType | |
| TimestampType | datetime.datetime 类型 |
| DayTimeIntervalType | datetime.timedelta类型 |

相关推荐
_落纸2 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE2 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha2 天前
SpringBoot
笔记·学习
Hello_Embed2 天前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中2 天前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
Grassto2 天前
RAG 从入门到放弃?丐版 demo 实战笔记(go+python)
笔记
Magnetic_h2 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
周周记笔记2 天前
学习笔记:第一个Python程序
笔记·学习
丑小鸭是白天鹅2 天前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin
潘达斯奈基~2 天前
《大数据之路1》笔记2:数据模型
大数据·笔记