【问题标题】:PySpark Dataframe: Changing two Columns at the same time based on conditionPySpark Dataframe:根据条件同时更改两列
【发布时间】:2017-11-23 20:29:49
【问题描述】:

我想知道是否有办法同时更改 PySpark Dataframe 的两列(或更多列)。现在我正在使用withColumn,但我不知道这是否意味着条件会被检查两次(这对于大型数据框来说太贵了)。此代码基本上检查其他两列(同一行)中的值,并基于此将两列更改为 None/null。

   condition =  is_special_id_udf(col("id"))) & should_hide_response_udf(col("response_created"))


     new_df = df.withColumn(
            "response_text",
            when(condition, None)
            .otherwise(col("response_text"))
        )

     new_df = df.withColumn(
            "response_created",
            when(condition, None)
            .otherwise(col("response_created"))
        )

【问题讨论】:

  • 请分享完整的代码和示例数据。您的代码不可重现。
  • 您真的需要这些数据吗?代码按预期工作我只是想知道是否有更好的方法来做同样的事情。
  • 您要创建同一列两次,您的问题是如何做到这一点?
  • 那是源代码中的一个类型。我纠正了它。我根据相同的条件修改了两个不同的列。现在我一个接一个地这样做。我想知道是否有更好的方法使用 DF API 或 RDD。谢谢。
  • 您是在谈论将列添加到同一个数据帧还是两个不同的数据帧(您的代码在获取原始数据帧时只会有一个新列)。此外,您正在使用需要 response_created 的条件,您的目标是覆盖它吗?

标签: python apache-spark pyspark


【解决方案1】:

首先,您可以简单地将 UDF 添加为新列,将其用于计算并删除它:

condition =  is_special_id_udf(col("id"))) & should_hide_response_udf(col("response_created"))

 new_df = df.withColumn("tmp", condition).withColumn(
        "response_text",
        when(col("tmp"), None)
        .otherwise(col("response_text"))
    ).withColumn(
        "response_created",
        when(col("tmp"), None)
        .otherwise(col("response_created"))
    ).drop("tmp")

如果您真的想生成两列,那么您可以创建一个结构列并将其展平(当然,将您需要的列添加到选择中):

new_df = df.withColumn(
        "myStruct",
        when(condition, None)
        .otherwise(struct(col("response_text"), col("response_created")))
    ).select("myStruct.*")

【讨论】:

  • 第二个选项很好,让我的答案过时了。
  • 我认为答案的第一部分是我正在寻找的,我想知道是否有一种方法可以不使用条件结果创建列但它看起来更干净。
猜你喜欢
  • 2018-05-14
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多