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类型 |

相关推荐
云半S一4 小时前
Agent学习总结补充:2
人工智能·经验分享·笔记·agent·学习分享
小飞在努力6 小时前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装
c语言·开发语言·c++·笔记
山川而川-R8 小时前
RK3588边缘计算:YOLOv8 使用Android NDK部署_笔记1
人工智能·笔记·yolo·安卓
饮水桶_T9 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
叼烟扛炮11 小时前
[LangChain] 学习笔记(026):模型根本没有记忆——「多轮对话」是你每次把历史重发一遍
笔记·学习·langchain
饮水桶_T13 小时前
HashMap笔记
开发语言·数据结构·笔记
星恒随风15 小时前
从0实现C++ AI大模型接入SDK(三):环境搭建与ChatSDK快速上手——实现我们的第一个AI聊天程序
linux·开发语言·c++·人工智能·笔记
Z21-X18 小时前
云原生运维学习笔记:Kubernetes Service 发现、类型与 kube-proxy 实战
运维·笔记·学习·云原生·kubernetes
sealaugh3218 小时前
powerbi学习笔记(day2)powerbi进阶
笔记·学习·powerbi
一只大鸽子18 小时前
游戏开发笔记11-Godot RPG游戏基础-优化-四方向攻击
笔记·游戏·godot