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

Casting a new derived column in a DataFrame from boolean to integer

假设我有一个 DataFrame x 具有以下架构:

xSchema = StructType([ \
    StructField("a", DoubleType(), True), \
    StructField("b", DoubleType(), True), \
    StructField("c", DoubleType(), True)])

然后我有了 DataFrame:

DataFrame[a :double, b:double, c:double]

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

x = x.withColumn('y', (x.a-x.b)/x.c > 1)

我的新架构是:

DataFrame[a :double, b:double, c:double, y: boolean]

但是,我希望第 y 列包含 0 表示错误,1 表示正确。

cast函数只能对列进行操作,不能对DataFrame进行操作,withColumn函数只能对DataFrame进行操作。如何添加新列并将其同时转换为整数?

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

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