如何在计算中使用PySpark数据框中包含的操作数?



我有一个PySpark数据框架,其中包含操作数(特别是大于,小于等)。我想使用这些操作数来计算使用数据框中的其他值的结果,并使用这个新数据创建一个新列。例如:

from pyspark.sql import Row
from pyspark.sql.functions import expr, when
df = spark.createDataFrame([
Row(id=1, value=3.0, operand='>', threshold=2. ),
Row(id=2, value=2.3, operand='>=', threshold=3. ),
Row(id=3, value=0.0, operand='==', threshold=0.0 )
])
df = df.withColumn('result', when(expr("value " + df.operand + " threshold"), True).otherwise(False))
df.show()

我希望得到以下结果:

|id|value|operand|threshold|result|
|--|-----|-------|---------|------|
|1 |  3.0|      >|      2.0|  true|
|2 |  2.3|     >=|      3.0| false|
|3 |  0.0|     ==|      0.0|  true|

却得到错误TypeError: Column is not iterable。我已经尝试了不同的机制来提取操作数值(即col("operand")),但没有成功。

NB -我欣赏使用==来确定双精度是否相等并不总是可靠的,但用例允许它。

这是我的动态解决方案:

from pyspark.sql.functions import udf
dynamic_condition_udf = udf(lambda value, operand, threshold: eval(f"{value} {operand} {threshold}"))
df.withColumn("result", dynamic_condition_udf("value", "operand", "threshold")).show()

输出
+---+-----+-------+---------+------+
| id|value|operand|threshold|result|
+---+-----+-------+---------+------+
|  1|  3.0|      >|      2.0|  true|
|  2|  2.3|     >=|      3.0| false|
|  3|  0.0|     ==|      0.0|  true|
+---+-----+-------+---------+------+

最新更新