2024-03-29 12:19:54 发布
网友
我有一个列为字符串的数据帧。 我想在PySpark中将列类型改为Double类型。
我是这样做的:
toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType()) changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
只是想知道,这是在跑步的时候做的正确方法吗 通过逻辑回归,我得到了一些错误,所以我想, 这就是麻烦的原因吗。
保留列的名称,并使用与输入列相同的名称来避免额外的列添加:
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
给出的答案足以解决这个问题,但我想分享另一种可能引入新版本Spark(我不确定)的方法,因此给出的答案没有抓住它。
我们可以使用col("colum_name")关键字访问spark语句中的列:
col("colum_name")
from pyspark.sql.functions import col , column changedTypedf = joindf.withColumn("show", col("show").cast("double"))
这里不需要自定义项。Column已经为^{} method提供了^{}实例:
Column
from pyspark.sql.types import DoubleType changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))
或短字符串:
changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))
其中规范字符串名称(也可以支持其他变体)对应于simpleString值。对于原子类型:
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>'
保留列的名称,并使用与输入列相同的名称来避免额外的列添加:
给出的答案足以解决这个问题,但我想分享另一种可能引入新版本Spark(我不确定)的方法,因此给出的答案没有抓住它。
我们可以使用
col("colum_name")
关键字访问spark语句中的列:这里不需要自定义项。} method 提供了^{} 实例:
Column
已经为^{或短字符串:
其中规范字符串名称(也可以支持其他变体)对应于
simpleString
值。对于原子类型:例如复杂类型
相关问题 更多 >
编程相关推荐