PySpark 如何迭代 Dataframe 列并更改数据类型?

Joe*_*Joe 1 python dataframe apache-spark apache-spark-sql pyspark

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

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

df = df.withColumn("COLUMN_X", df["COLUMN_X"].cast(IntegerType()))
Run Code Online (Sandbox Code Playgroud)

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

谢谢。

bla*_*hop 5

当 type 等于时,您可以循环df.dtypes并强制转换为:bigintdecimal(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)
Run Code Online (Sandbox Code Playgroud)