我有一个列作为字符串的数据框。 我想在 PySpark 中将列类型更改为 Double 类型。
以下是方式,我做到了:
toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
只是想知道,这是运行时的正确方法吗 通过逻辑回归,我得到了一些错误,所以我想知道, 这就是麻烦的原因吗?
最佳答案
这里不需要UDF。 列
已提供cast
method与 DataType
实例:
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>'
关于python - 如何在 PySpark 中将数据框列从 String 类型更改为 Double 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284620/