這個問題在這里已經有了答案: IF Then ELSE 的 Spark 等效 4 個答案 4天前關閉。
我正在嘗試在 python 函式中使用 if 條件,然后使用它對資料框值進行一些計算。
#init data
--- ---- ---- ------
| id|team|game|result|
--- ---- ---- ------
| 1| A|Home| |
| 2| A|Away| |
| 3| B|Home| |
| 4| B|Away| |
| 5| C|Home| |
| 6| C|Away| |
| 7| D|Home| |
| 8| D|Away| |
--- ---- ---- ------
### I wanna replace the value result and I tried use a function
def replace_result(team_name,game_kind,result):
if col('team') == team_name and col('game') == game_kind:
return result
else:
return col('result')
df = df.withColumn('result',replace_result('A','Away','0-1')
但給了我錯誤
ValueError:無法將列轉換為布林值:請使用 '&' 表示 'and'、'|' 構建 DataFrame 布爾運算式時,為 'or','~' 為 'not'。
我的問題是
是否可以使用使用 Pyspark 資料框列的 if 條件?
謝謝
uj5u.com熱心網友回復:
是的,有內置spark.sql的函式被呼叫when并且otherwise可以做到這一點。
使用以下資料框。
df.show()
--- ---- ----
| id|team|game|
--- ---- ----
| 1| A|Home|
| 2| A|Away|
| 3| B|Home|
| 4| B|Away|
| 5| C|Home|
| 6| C|Away|
| 7| D|Home|
| 8| D|Away|
--- ---- ----
您可以通過以下方式使用when和otherwise條件。
from pyspark.sql import functions
df = (df.withColumn("result",
functions.when((df["team"] == "A") & (df["game"] == "Home"), "WIN")
.when((df["team"] == "B") & (df["game"] == "Away"), "WIN")
.when((df["team"] == "D") & (df["game"] == "Home"), "WIN")
.when((df["team"] == "D") & (df["game"] == "Away"), "WIN")
.otherwise("LOSS")))
df.show()
--- ---- ---- ------
| id|team|game|result|
--- ---- ---- ------
| 1| A|Home| WIN|
| 2| A|Away| LOSS|
| 3| B|Home| LOSS|
| 4| B|Away| WIN|
| 5| C|Home| LOSS|
| 6| C|Away| LOSS|
| 7| D|Home| WIN|
| 8| D|Away| WIN|
--- ---- ---- ------
uj5u.com熱心網友回復:
使用 DataFrame 時,您需要為自定義代碼使用 udf。
https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.udf.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/418188.html
標籤:
