将值与 pyspark 中的特定误差范围进行比较

时间:2021-02-08 14:06:52

标签: apache-spark pyspark apache-spark-sql compare pyspark-dataframes

有没有办法比较 pyspark 中 double 类型的两个值,并具有指定的误差幅度? 本质上与此 post 类似,但在 pyspark 中。

类似于:

df=#some dataframe with 2 columns RESULT1 and RESULT2

df=withColumn('compare', when(col('RESULT1')==col('RESULT2') +/- 0.05*col('RESULT2'), lit("match")).otherwise(lit("no match"))

但以更优雅的方式?

2 个答案:

答案 0 :(得分:1)

您可以使用 between 作为条件:

df2 = df.withColumn(
    'compare',
    when(
        col('RESULT1').between(0.95*col('RESULT2'), 1.05*col('RESULT2')), 
        lit("match")
    ).otherwise(
        lit("no match")
    )
)

答案 1 :(得分:1)

你也可以写成 |RESULT1 - RESULT2| <= 0.05 * RESULT2 :

from pyspark.sql import functions as F

df1 = df.withColumn(
    'compare',
    F.when(
        F.abs(F.col('RESULT1') - F.col("RESULT2")) <= 0.05 * F.col("RESULT2"),
        F.lit("match")
    ).otherwise(F.lit("no match"))
)