問題看起來很簡單,但找不到簡單的方法來解決它。
我正在嘗試在 中動態創建新列selectExpr,但它不接受串列作為引數。實作它的最佳方法是什么?(withColumn由于stackoverflowexception
輸入,Multiple不是一個選項:
a | b
-------
1 | zzz
2 | xxx
嘗試過這樣的事情
sample_new_cols = {"s":"ran-s",
"ts": "current_timestamp()",
}
df = df.selectExpr('*',
[
f"{definition} as {name}"
for name, definition in sample_new_cols.items()
]
)
它的輸出將是
a | b | s | ts
------------|-----------
1 |zzz|ran-s|2021-12-01 08:10:21
2 |xxx|ran-s|2021-12-01 08:10:21
uj5u.com熱心網友回復:
你幾乎明白了:
- 對于字串靜態列定義,您需要參考值(例如。
'ran-s') - 并且在
selectExpr,您需要*在列陣列之前使用星號
sample_new_cols = {
"s": "'ran-s'",
"ts": "current_timestamp()",
}
df1 = df.selectExpr('*', *[
f"{definition} as {name}"
for name, definition in sample_new_cols.items()
])
df1.show()
# --- --- ----- -----------------------
#|a |b |s |ts |
# --- --- ----- -----------------------
#|1 |zzz|ran-s|2021-12-01 14:23:14.779|
#|2 |xxx|ran-s|2021-12-01 14:23:14.779|
# --- --- ----- -----------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372260.html
標籤:Python 阿帕奇火花 火花 apache-spark-sql
上一篇:根據其他資料框的范圍創建資料框
