gpt4 book ai didi

python - 将 DataFrame 中的新派生列从 bool 值转换为整数

转载 作者:太空狗 更新时间:2023-10-29 21:31:08 42 4
gpt4 key购买 nike

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

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

然后我有了 DataFrame:

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

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

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 进行操作。如何添加新列并将其同时转换为整数?

最佳答案

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

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

关于python - 将 DataFrame 中的新派生列从 bool 值转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33354571/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com