PySpark 如何遍历 Dataframe 列并更改数据类型? [英] PySpark how to iterate over Dataframe columns and change data type?

查看:52
本文介绍了PySpark 如何遍历 Dataframe 列并更改数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迭代 Spark 数据帧(使用 Pyspark)并找到 Decimal(38,10) 的数据类型的最佳方法是什么 -> 将其更改为 Bigint(并将所有数据重新保存到相同的数据帧))?

What is the best way to iterate over Spark Dataframe (using Pyspark) and once find data type of Decimal(38,10) -> change it to Bigint (and resave all to the same dataframe)?

我有一部分用于更改数据类型 - 例如:

I have a part for changing data types - e.g.:

df = df.withColumn("COLUMN_X", df["COLUMN_X"].cast(IntegerType()))

但试图找到并与迭代集成..

but trying to find and integrate with iteration..

谢谢.

推荐答案

当 type 等于 时,您可以遍历 df.dtypes 并强制转换为 bigint十进制(38,10) :

You can loop through df.dtypes and cast to bigint when type is equal to decimal(38,10) :

from pyspark.sql.funtions import col

select_expr = [
    col(c).cast("bigint") if t == "decimal(38,10)" else col(c) for c, t in df.dtypes
]

df = df.select(*select_expr)

这篇关于PySpark 如何遍历 Dataframe 列并更改数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆