Pyspark -是否可以使用“Map表”根据现有值获得所需值

zte4gxcn  于 2022-11-21  发布在  Spark
关注(0)|答案(1)|浏览(105)

我想知道是否有可能使用另一个 Dataframe /表作为Map表。这里是我能描述的最好的。
dfA(原始数据集)
下面是原始数据集。这是我们要根据查找更改的数据集
| 名称名称名称|交易ID|警示旗标|
| - -|- -|- -|
| 约翰·史密斯|小行星93818|错误数学|
| 无名氏|小行星91982|行无效|
dfB(查阅表格)
下表将引用警报标志以及每个警报标志应等于什么。
| 警报标志旧|警报_标记_新|
| - -|- -|
| 错误数学|计算不正确|
| 行无效|无效事务处理|
我想知道的是。我们能不能查一下。比如

dfA = (
 dfA
 .withColumn('Alert_Flag', LOOKUP on dfB. if (dfA.ALERT_FLAG) in dfB.ALERT_FLAG_OLD then VALUE = ALERT_FLAG_NEW

if (ALERT_FLAG)只是表示如果dfB中存在警报标志,则使用find它的新值。
这种事可能吗?
还没有尝试过任何东西,因为我真的不知道如何开始它

8yoxcaq7

8yoxcaq71#

首先执行left-join,然后使用简单的when-otherwise构造,如下所示:

from pyspark.sql.functions import col, when

dfA = spark.createDataFrame([("John Smith", 93818, "Bad Math"), ("Jane Doe", 91982, "Invalid Row")], "Name: string, TransactionID: int, Alert_flag: string")
dfB = spark.createDataFrame([("Bad Math", "Incorrect Calculations"), ("Invalid Row", "Invalid Transaction")], "Alert_flag_OLD: string, Alert_flag_NEW: string")

dfC = dfA.join(dfB, col("Alert_flag") == col("Alert_flag_OLD"), "left")
dfC.withColumn("Alert_flag", when(col("Alert_flag_NEW").isNotNull(), col("Alert_flag_NEW"))).select(["Name", "TransactionID", "Alert_flag"]).show()

+----------+-------------+----------------------+
|Name      |TransactionID|Alert_flag            |
+----------+-------------+----------------------+
|John Smith|93818        |Incorrect Calculations|
|Jane Doe  |91982        |Invalid Transaction   |
+----------+-------------+----------------------+

相关问题