【问题标题】:How to multiply two columns in a spark dataframe如何将火花数据框中的两列相乘
【发布时间】:2019-02-24 06:12:18
【问题描述】:

假设我有一个名为“orderitems”的数据框,其架构如下

    DataFrame[order_item_id: int, order_item_order_id: int, order_item_product_id: int, order_item_quantity: int, order_item_subtotal: float, order_item_product_price: float]

所以作为检查数据质量的一部分,我需要确保所有行都满足公式:order_item_subtotal = (order_item_quantity*order_item_product_price)。 为此,我需要添加一个名为“valid”的单独列,对于所有满足上述公式的行,它应该具有“Y”作为值,对于所有其他行,它应该具有“N”作为值。 我决定使用 when() 和 else() 以及 withColumn() 方法,如下所示。

    orderitems.withColumn("valid",when(orderitems.order_item_subtotal != (orderitems.order_item_product_price * orderitems.order_item_quantity),'N').otherwise("Y"))

但它在错误下方返回我:

    TypeError: 'Column' object is not callable

我知道发生这种情况是因为我试图将两个列对象相乘。但我不知道如何解决这个问题,因为我仍在 spark 的学习过程中。 我想知道,如何解决这个问题。我正在使用带有 Python 的 Spark 2.3.0

【问题讨论】:

    标签: apache-spark pyspark


    【解决方案1】:

    试试这样的:

    from pyspark.sql.functions import col,when
    orderitems.withColumn("valid",
              when(col("order_item_subtotal") != (col("order_item_product_price") * col("order_item_quantity")),"N")
              .otherwise("Y")).show()
    

    【讨论】:

    • 我已更正错字。但是这种方法对我不起作用。我正在使用带有 Python 的 Spark 2.3.0。 "=!=" 向我抛出“无效语法”
    • @akhilpathirippilly =!= 是 Scala 的东西,!= 在 Python 中很好
    • 它的工作:)。令人惊讶的是,我在问题陈述中提到的上述代码也有效。我不确定是什么导致它之前抛出错误。无论如何感谢您花时间研究这个问题。
    【解决方案2】:

    这可以通过 spark UDF 函数来实现,这些函数在执行行操作时非常有效。 在运行此代码之前,请确保您进行的比较应该具有相同的数据类型。

    def check(subtotal, item_quantity, item_product_price):
      if subtotal == (item_quantity * item_product_price):
        return "Y"
      else:
        return "N"
    
    validate = udf(check)
    
    orderitems = orderitems.withColumn("valid", validate("order_item_subtotal", "order_item_quantity", "order_item_product_price"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-06
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      相关资源
      最近更新 更多