首页 > 解决方案 > 使用 select 和 for 循环替换现有列中的值

问题描述

根据 Sparks 文档,不再推荐这种设计。

    for col in ['fl_ab_delivery_rbc', 'dr_ab_delivery_rbc', 'ab_delivery_rbc', 'wslr_delivery_rbc']:
        df = (
            df
            .withColumn(f"proposed_{col}", F.col(f"final_{col}"))
        )

由于这个道理。

在此处输入图像描述

我正在尝试提出一个优雅的解决方案来解决这个警告。我使用这样的解决方案来创建以前从未创建过的全新列。但是,由于该列已经存在并且设置在更远的位置,它基本上只是添加了另一列,并且我得到了一个编译错误,因为有重复的列。

    col = ['fl_ab_delivery_rbc', 'dr_ab_delivery_rbc', 'ab_delivery_rbc', 'wslr_delivery_rbc']
    df = (
        df
        .select(
            '*',
            *[F.col(f"final_{c}").alias(f"proposed_{c}") for c in col]
        )
    )

关于如何用“final_{c}”列中的值替换现有列值而不创建重复项的任何想法?

最初,我的猜测是改变.select("*")部分?

标签: apache-sparkpyspark

解决方案


好吧,我想我找到了答案!

这对我有用

col = {'fl_ab_deliver_rbc', 'dr_ab_delivery_rbc', 'ab_delivery_rbc', 'wslr_delivery_rbc'}

df = (
    df
    .select(
        *(F.col(c) for c in df.columns if c not in col),
        *(F.col(f"final_{c}").alias(f"proposed_{c}") for c in col)
    )
)


推荐阅读