首页 > 解决方案 > Python exec() 没有创建 PySpark 数据框

问题描述

我正在尝试在 spark 数据框上创建一个附加列。新列由串联的列列表 (col_list) 组成。一切正常,直到我实际执行exec()行。未创建数据框“tb”。

我正在使用 exec() 因为“col_list”列表是动态生成的。

不知道为什么exec()不能创建新的数据框'tb':

这是代码:

exec("tb = table_df.withColumn('TestPrimaryKey',{0})".format(col_list))

标签: pythonpysparkdatabricks

解决方案


如果要在 exec 函数中获取值,一种方法是使用列表并附加结果:

exec_return = []
exec("exec_return.append('value')")
value = exec_return[0]

在这种情况下,要获得 tb 值,您可以这样做:

exec_return = []
exec("exec_return.append(table_df.withColumn('TestPrimaryKey',{0}))".format(col_list))
tb = exec_return[0]

推荐阅读