将数据框架中的新派生列从布尔值转换为整数

Mic*_*hal 8 python apache-spark apache-spark-sql pyspark pyspark-sql

假设我有一个x带有此架构的DataFrame :

xSchema = StructType([ \
    StructField("a", DoubleType(), True), \
    StructField("b", DoubleType(), True), \
    StructField("c", DoubleType(), True)])
Run Code Online (Sandbox Code Playgroud)

然后我有DataFrame:

DataFrame[a :double, b:double, c:double]
Run Code Online (Sandbox Code Playgroud)

我想有一个整数派生列.我能够创建一个布尔列:

x = x.withColumn('y', (x.a-x.b)/x.c > 1)
Run Code Online (Sandbox Code Playgroud)

我的新架构是:

DataFrame[a :double, b:double, c:double, y: boolean]
Run Code Online (Sandbox Code Playgroud)

但是,我希望列y包含0表示False,1表示True表示.

cast功能只能在列上操作,而不能在a上操作,DataFrame并且该withColumn功能只能在a上运行DataFrame.如何添加新列并同时将其转换为整数?

zer*_*323 12

您使用的表达式求值为列,因此您可以像这样直接转换:

x.withColumn('y', ((x.a-x.b) / x.c > 1).cast('integer')) # Or IntegerType()
Run Code Online (Sandbox Code Playgroud)