将 DataFrame 中的新派生列从布尔值转换为整数 [英] Casting a new derived column in a DataFrame from boolean to integer

查看:57
本文介绍了将 DataFrame 中的新派生列从布尔值转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a DataFrame x with this schema:

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

然后我有数据帧:

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

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

I would like to have an integer derived column. I am able to create a boolean column:

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

我的新架构是:

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

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

However, I would like column y to contain 0 for False and 1 for True.

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

The cast function can only operate on a column and not a DataFrame and the withColumn function can only operate on a DataFrame. How to I add a new column and cast it to integer at the same time?

推荐答案

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

Expression you use evaluates to column so you can cast directly like this:

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

这篇关于将 DataFrame 中的新派生列从布尔值转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆