如何在pysp中将Dataframe列从String类型更改为Double类型

2024-03-29 12:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我是这样做的:

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

只是想知道,这是在跑步的时候做的正确方法吗 通过逻辑回归,我得到了一些错误,所以我想, 这就是麻烦的原因吗。


Tags: 数据lambda字符串类型showlabel中将pyspark
3条回答

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

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

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

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

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

这里不需要自定义项。Column已经为^{} method提供了^{}实例:

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>'

相关问题 更多 >