下面是輸入資料框。
----------- --------- ------------------ ---------------------- -----------
| DATE | ID |sal | vat | flag |
----------- --------- ------------------ ---------------------- ------------
|10-may-2022| 1 | 1000.0| 12.0 1 |
|12-may-2022| 2 | 50.0| 6.0| 1 |
----------- --------- ------------------ ---------------------- ------------
我想根據標志列執行以下操作
如果標志列是 1,我將執行以下操作。
df = srcdf.withColumn("sum",col("sal")*2)
display(df)
如果標志列是 2,我將執行以下操作。
df = srcdf.withColumn("sum",col("sal")*4)
display(df)
下面是我使用的代碼。
flag = srcdf.select(col("flag"))
if flag == 1 :
df = srcdf.withColumn("sum",col("sal")*2)
display(df)
else:
df = srcdf.withColumn("sum",col("sal")*4)
display(df)
當我使用上述內容時,我收到語法錯誤。有沒有其他方法可以使用 pyspark 條件陳述句來實作這一點。
謝謝你。
uj5u.com熱心網友回復:
這個問題可能重復。
您需要使用when(或不使用)otherwisefrom pyspark.sql.functions。
from pyspark.sql.functions import when, col
df = srcdf\
.withColumn("sum", when(col("flag") == 1, col("sal") * 2)\
.when(col("flag") == 2, col("sal") * 4)
)
或者
from pyspark.sql.functions import when, col
df = srcdf\
.withColumn("sum", when(col("flag") == 1, col("sal") * 2)\
.otherwise(col("sal") * 4)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/492170.html
