gpt4 book ai didi

python - pyspark sql : Create a new column based on whether a value exists in a different DataFrame's column

转载 作者:太空宇宙 更新时间:2023-11-04 04:41:07 25 4
gpt4 key购买 nike

我试着关注 this answer但我的问题略有不同。

我有两个 pyspark 数据帧 df2bears2。两者都有一个整数变量,我想创建一个像这样的伪代码的 bool 值:

df3 = df2.withColumn("game", (df2.week_id.isin(bears2.week_if), 1,0))

基本上,如果 df2 的值存在于 bears2 的相应列中,我想要一个 1 否则一个 0

我尝试了另一个问题中的 expr(),但无法让它工作。它看起来像这样:

new_column_1 = F.expr(
"""IF(df2.week_id IN(bears2.week_if), 1, 0))"""
)

最佳答案

您目前不能像 pyspark-sql 1 那样使用 IN 。相反,您必须加入 DataFrames。

尝试这样的事情:

from pyspark.sql.functions import col, when
df3 = df2.withColumn("id", col("week_id")).alias("df2")\
.join(bears2.withColumn("id", col("week_if")).alias("bears2"), on="id", how="left")\
.select("df2.*", when(col("bears2.id").isNotNull(), 1).otherwise(0))

要使连接正常工作,连接键列必须存在于两个 DataFrame 中。出于这个原因,我首先调用 withColumn("id", ...) 将列重命名为与连接相同的值。

接下来我们进行左连接以保留 df2 中的所有列。最后,我们选择 df2 中的所有列并使用 pyspark.sql.functions.when()创建 bool 列。

when() 的第一个参数是一个条件。如果为 True,则返回第二个参数。如果不是,则使用 otherwise() 中的值。

关于python - pyspark sql : Create a new column based on whether a value exists in a different DataFrame's column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50606132/

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