ChatGPT解决这个技术问题 Extra ChatGPT

如何在 PySpark 中将数据框列从 String 类型更改为 Double 类型?

我有一个列为字符串的数据框。我想在 PySpark 中将列类型更改为 Double 类型。

以下是我做的方式:

toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))

只是想知道,这是正确的方法吗,因为在运行逻辑回归时,我遇到了一些错误,所以我想知道,这是否是麻烦的原因。


1
10465355

这里不需要UDF。 Column 已经为 cast method 提供了 DataType instance

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))

或短字符串:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))

其中规范字符串名称(也可以支持其他变体)对应于 simpleString 值。所以对于原子类型:

from pyspark.sql import types 

for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', 
          'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', 
           'LongType', 'ShortType', 'StringType', 'TimestampType']:
    print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp

例如复杂类型

types.ArrayType(types.IntegerType()).simpleString()   
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'

使用 col 函数也可以。 from pyspark.sql.functions import colchangedTypedf = joindf.withColumn("label", col("show").cast(DoubleType()))
cast() 参数的可能值是什么(“字符串”语法)?
我不敢相信 Spark 文档在数据类型的有效字符串上是多么简洁。我能找到的最接近的参考是: docs.tibco.com/pub/sfire-analyst/7.7.1/doc/html/en-US/…
如何一次转换多个列?
如何将 nullable 更改为 false?
Z
ZygD

通过使用与输入列相同的名称来保留列的名称并避免额外的列添加:

from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

谢谢 我正在寻找如何保留原始列名
Spark将识别的短字符串数据类型的列表是否存在?
该解决方案在循环中也可以出色地工作,例如 from pyspark.sql.types import IntegerType for ftr in ftr_list: df = df.withColumn(f, df[f].cast(IntegerType()))
@Quetzalcoatl 你的代码是错误的。 f 是什么?您在哪里使用 ftr
是的,谢谢——“f”应该是“ftr”。其他人可能已经意识到了这一点。
Z
ZygD

给定的答案足以解决这个问题,但我想分享另一种可能引入新版本 Spark 的方式(我不确定)所以给定的答案没有抓住它。

我们可以使用 col("colum_name") 关键字到达 spark 语句中的列:

from pyspark.sql.functions import col
changedTypedf = joindf.withColumn("show", col("show").cast("double"))

谢谢!使用 'double' 比可能还需要导入的 DoubleType() 更优雅。
Z
ZygD

PySpark 版本:

df = <source data>
df.printSchema()

from pyspark.sql.types import *

# Change column type
df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
df_new.printSchema()
df_new.select("myColumn").show()

A
Abhishek Choudhary

解决方案很简单 -

toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))