根据其他列中满足的条件添加列

2024-05-12 21:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是PySpark的新手,我现在面临着以下问题的挑战。 我有一个火花df如下

DeviceID     max(A)    max(B)    max(INUT)
0023002      2.5       3.7       8.1
0023045      2.2       1.3       11.3
0023008      4.7       2.3       1.9

如何添加另一列作为“Status”,其中的值将基于以下逻辑。你知道吗

if 0.20 * max(INUT) > max(max(A),max(B)) then Status = 'Imbalance' else 'Balance'

上述逻辑预期将产生以下数据帧。你知道吗

DeviceID     max(A)    max(B)    max(INUT)    Status
0023002      2.5       3.7       8.1          'Balance'
0023045      2.2       1.3      11.3          'ImBalance'
0023008      4.7       2.3       1.9          'Balance'

现在要实现上面的df,下面是我正在使用的代码

from pyspark.sql.function import col
import pyspark.sql.function as F
df_final = df.withColumn(
             'Status',
             F.when(col('max(INUT)')*0.20 > F.greatest(col('max(A)'),col('max(B)'),
             'Imbalance')\
         .otherwise('Balance')

上面的代码段引发了一个错误

AttributeError: 'tuple' object has no attribute 'otherwise'

我错过了什么?如有任何提示,将不胜感激。你知道吗


Tags: importdfsqlstatusfunctioncol逻辑max
1条回答
网友
1楼 · 发布于 2024-05-12 21:26:51

有一些小的语法错误,这是您的最终代码:

import pyspark.sql.functions as F

df = spark.createDataFrame(
[("0023002", 2.5, 3.7, 8.1),
("0023045", 2.2, 1.3, 11.3),
("0023008", 4.7, 2.3, 1.9)], ["DeviceID", "max_A", "max_B", "max_INUT"])

df_final = df.withColumn('Status', \
             F.when(F.col('max_INUT')*0.20 > F.greatest(F.col('max_A'),F.col('max_B')), 'Imbalance') \
         .otherwise('Balance'))

以及一些评论:

  1. 要使用pyspark.sql.functions中的函数,只需使用F alias。你不需要导入两次。你知道吗
  2. 缺少一些括号
  3. 我还替换了max(A) -> max_A,因为我相信它更容易阅读

输出:

+    +  -+  -+    +    -+
|DeviceID|max_A|max_B|max_INUT|   Status|
+    +  -+  -+    +    -+
| 0023002|  2.5|  3.7|     8.1|  Balance|
| 0023045|  2.2|  1.3|    11.3|Imbalance|
| 0023008|  4.7|  2.3|     1.9|  Balance|
+    +  -+  -+    +    -+

相关问题 更多 >