我试着关注 this answer但我的问题略有不同。
我有两个 pyspark 数据帧 df2
和 bears2
。两者都有一个整数变量,我想创建一个像这样的伪代码的 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()
中的值。
我是一名优秀的程序员,十分优秀!