【发布时间】:2020-09-09 20:02:01
【问题描述】:
下面的代码将我的参考 df 的值和列名映射到我的实际数据集,查找完全匹配,如果找到完全匹配,则返回 OutputValue。但是,我正在尝试添加规则,即当PrimaryValue = DEFAULT 也返回OutputValue。
我正在尝试解决此问题的解决方案是创建一个具有空值的新数据框 - 因为下面的代码没有提供匹配项。因此,下一步将针对空值,其对应的PrimaryValue = DEFAULT 将空值替换为OutputValue。
#create a map based on columns from reference_df
map_key = concat_ws('\0', final_reference.PrimaryName, final_reference.PrimaryValue)
map_value = final_reference.OutputValue
#dataframe of concatinated mappings to get the corresponding OutputValues from reference table
d = final_reference.agg(collect_set(array(concat_ws('\0','PrimaryName','PrimaryValue'), 'OutputValue')).alias('m')).first().m
#display(d)
#iterate through mapped values
mappings = create_map([lit(i) for i in chain.from_iterable(d)])
#dataframe with corresponding matched OutputValues
dataset = datasetM.select("*",*[ mappings[concat_ws('\0', lit(c), col(c))].alias(c_name) for c,c_name in matched_List.items()])
display(dataset)
【问题讨论】:
-
你的意思是当来自
primaryLookupAttributeName_List的请求的col-name在datasetMatchedPortfolio中不存在时会产生错误?所以你想添加一个默认名称来通过错误? -
@jxc,所以没有错误。它只是用空值填充列。数据集永远不会包含
DEFAULT,它将具有常规值。当PrimaryLookupAttributeName是默认值时,我想用相应的OutputItemNameByValue替换那些空值(未找到匹配项)。我会用更多信息更新我的问题! -
很可能,您只需要合并,例如:
coalesce(mappings[concat_ws('\0', lit(c), col(c))], lit("DEFAULT")).alias(c_name)。确保导入 pyspark.sql.functions.coalesce -
@jxc,对不起,您是打算对空 df 执行此操作还是将其作为我最初的
datasetPrimaryAttributes_False =的一部分包含在内 -
@jxc,您是否建议在此处包含带有 if/else/elif 循环的 udf?我有 3 种匹配情况:1)如果找到匹配,则复制 outputValue,2)如果默认,复制 outputValue,3)如果根本没有匹配并且 null,“找不到查找”。否则,到目前为止,我的想法是继续构建过滤数据框,直到我的最后一个案例并且所有数据集值都有相应的更新值。
标签: python dataframe pyspark apache-spark-sql mapping