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

标签 python apache-spark dataframe pyspark apache-spark-sql

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

以下是方式,我做到了:

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

只是想知道,这是运行时的正确方法吗 通过逻辑回归,我得到了一些错误,所以我想知道, 这就是麻烦的原因吗?

最佳答案

这里不需要UDF。 已提供cast methodDataType 实例:

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/

相关文章:

python - 如何在 Python 中创建全零数据框

python - 检查输入是否是循环中的字符串

elasticsearch - Spark查询花费的时间太长

python - 向图像添加泊松噪声

apache-spark - 处理 Databricks 自动加载器中的重复项

apache-spark - 为什么spark在sql查询的末尾追加 'WHERE 1=0'

r - 从数据框中提取重复行

python - 将数据帧值与字典中的键范围进行比较并返回值

python - 如何在Python中存储一对一关系表以便快速查找?

android - 模糊测试时在 Android 上进行进程监控