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

Posted

技术标签:

【中文标题】将 DataFrame 中的新派生列从布尔值转换为整数【英文标题】:Casting a new derived column in a DataFrame from boolean to integer 【发布时间】:2015-10-26 20:02:14 【问题描述】:

假设我有一个具有此架构的 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 代表 False 和 1 代表 True。

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

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于将 DataFrame 中的新派生列从布尔值转换为整数的主要内容,如果未能解决你的问题,请参考以下文章

将 Pyspark Dataframe 列从数组转换为新列

Hive:将字符串转换为布尔值

ValueError 1:无法将列转换为布尔值:请使用 '&' 表示 'and'、'|' for 'or', '~' for 'not' 在构建 DataFrame 布尔表达式时

Pandas 映射到 TRUE/FALSE 作为字符串,而不是布尔值

将 pandas 数据框列从十六进制字符串转换为 int

bind_rows_(x, .id) 中的错误:无法将列从因子转换为数字