如何将列表传递给 pyspark 中的 selectExpr 方法?
How to pass list to the selectExpr method in pyspark?
问题看起来很简单,但找不到简单的方法来解决。
我正在尝试在 selectExpr
中动态创建新列,但它不接受列表作为参数。实现它的最佳方法是什么? (多个 withColumn
不是一个选项,因为 Whosebugexception
输入:
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
你快明白了:
- 对于字符串静态列定义,您需要引用值(例如
'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|
#+---+---+-----+-----------------------+
问题看起来很简单,但找不到简单的方法来解决。
我正在尝试在 selectExpr
中动态创建新列,但它不接受列表作为参数。实现它的最佳方法是什么? (多个 withColumn
不是一个选项,因为 Whosebugexception
输入:
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
你快明白了:
- 对于字符串静态列定义,您需要引用值(例如
'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|
#+---+---+-----+-----------------------+