pyspark - 使用 pyspark 基于 if 和 else 条件创建新列
问题描述
我有 2 个 spark 数据框,我想根据以下条件将名为“seg”的新列添加到数据框 df2
- 如果 df1.colx 中存在 df2.colx 值。
我在 pyspark 中尝试了以下操作,但它抛出异常。
cc002 = df2.withColumn('seg',F.when(df2.colx == df1.colx,"True").otherwise("FALSE"))
- df1:
id colx coly
1 678 56789
2 900 67890
3 789 67854
- df2
Name colx
seema 900
yash 678
deep 800
harsh 900
- 我的预期输出是
Name colx seg
seema 900 True
harsh 900 True
yash 678 True
deep 800 False
请帮助我更正给定的 pyspark 代码或提出更好的方法。
解决方案
如果我正确理解你的问题你想要做的是这个
res = df2.join(
df1,
on="colx",
how = "left"
).select(
"Name",
"colx"
).withColumn(
"seg",
F.when(F.col(colx).isNull(),F.lit(True)).otherwise(F.lit(False))
)
让我知道这是否是您想要的解决方案。
我很糟糕,我确实匆忙写了错误的代码,下面是更正的代码
import pyspark.sql.functions as F
df1 = sqlContext.createDataFrame([[1,678,56789],[2,900,67890],[3,789,67854]],['id', 'colx', 'coly'])
df2 = sqlContext.createDataFrame([["seema",900],["yash",678],["deep",800],["harsh",900]],['Name', 'colx'])
res = df2.join(
df1.withColumn(
"check",
F.lit(1)
),
on="colx",
how = "left"
).withColumn(
"seg",
F.when(F.col("check").isNotNull(),F.lit(True)).otherwise(F.lit(False))
).select(
"Name",
"colx",
"seg"
)
res.show()
+-----+----+-----+
| Name|colx| seg|
+-----+----+-----+
| yash| 678| true|
|seema| 900| true|
|harsh| 900| true|
| deep| 800|false|
+-----+----+-----+
推荐阅读
- actions-on-google - 谷歌助手默认后备退出代码
- database - sequelize 在特定条件下更改数据
- python - 如何将 3 项元组转换为字典
- python - 箱须图上的散景悬停工具提示
- python-3.x - 如何在Python3中获取给定html中所有元素的文本?
- excel - 如何从 2 列中获取最大数量和名称?(Excel)
- python - 在每行上打印有限数量的列表(python)
- postgresql - 我真的需要 Bridge Tables 上的标识字段吗?
- javascript - 绳索物理 - 绳索在重力作用下无法正确移动
- wso2 - WSO2 身份服务器 - 用户禁用在服务器重新启动之前不起作用