我有一个列为字符串的数据框。我想在 PySpark 中将列类型更改为 Double 类型。
以下是我做的方式:
toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
只是想知道,这是正确的方法吗,因为在运行逻辑回归时,我遇到了一些错误,所以我想知道,这是否是麻烦的原因。
这里不需要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>'
通过使用与输入列相同的名称来保留列的名称并避免额外的列添加:
from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
from pyspark.sql.types import IntegerType for ftr in ftr_list: df = df.withColumn(f, df[f].cast(IntegerType()))
f
是什么?您在哪里使用 ftr
?
给定的答案足以解决这个问题,但我想分享另一种可能引入新版本 Spark 的方式(我不确定)所以给定的答案没有抓住它。
我们可以使用 col("colum_name")
关键字到达 spark 语句中的列:
from pyspark.sql.functions import col
changedTypedf = joindf.withColumn("show", col("show").cast("double"))
'double'
比可能还需要导入的 DoubleType()
更优雅。
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()
解决方案很简单 -
toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
col
函数也可以。from pyspark.sql.functions import col
、changedTypedf = joindf.withColumn("label", col("show").cast(DoubleType()))