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

Abh*_*ary 74 python dataframe apache-spark apache-spark-sql pyspark

我有一个数据框,列为String.我想在PySpark中将列类型更改为Double类型.

以下是方式,我做了:

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

只是想知道,这是通过Logistic回归运行的正确方法,我遇到了一些错误,所以我想知道,这是问题的原因.

zer*_*323 131

这里不需要UDF.Column已经提供了实例的cast方法DataType:

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))
Run Code Online (Sandbox Code Playgroud)

或短串:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))
Run Code Online (Sandbox Code Playgroud)

其中规范字符串名称(也可以支持其他变体)对应于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()}")
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

例如复杂的类型

types.ArrayType(types.IntegerType()).simpleString()   
Run Code Online (Sandbox Code Playgroud)
'array<int>'
Run Code Online (Sandbox Code Playgroud)
types.MapType(types.StringType(), types.IntegerType()).simpleString()
Run Code Online (Sandbox Code Playgroud)
'map<string,int>'
Run Code Online (Sandbox Code Playgroud)

  • 使用`col`函数也可以.`from pyspark.sql.functions import col`,`changedTypedf = joindf.withColumn("label",col("show").cast(DoubleType()))` (2认同)

小智 41

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

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我一直在寻找如何保留原始列名称 (2认同)

ser*_*bay 8

给定的答案足以解决问题,但是我想分享另一种可能引入新版本Spark的方式(我不确定),因此给定的答案未能解决。

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

from pyspark.sql.functions import col , column
changedTypedf = joindf.withColumn("show", col("show").cast("double"))
Run Code Online (Sandbox Code Playgroud)


Cri*_*ian 6

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()
Run Code Online (Sandbox Code Playgroud)