pyspark 如何在数据库中传递一个 Dataframe 作为笔记本参数?

pdtvr36n  于 2023-01-08  发布在  Spark
关注(0)|答案(3)|浏览(199)

我有一个需求,其中我需要将pyspark Dataframe 作为笔记本参数传递给子笔记本。本质上,子笔记本几乎没有参数类型为 Dataframe 的函数来执行某些任务。现在的问题是,我无法使用将 Dataframe 传递给此子笔记本(不将其写入临时目录)

dbutils.notebook.run(<notebookpath>, timeout, <arguments>)

我尝试引用此url-Return a dataframe from another notebook in databricks
然而,我仍然有点困惑,我如何返回一个 Dataframe 从子笔记本到父笔记本,并从父笔记本到另一个子笔记本。
我试着写下面的代码-

tempview_list = ["tempView1", "tempView2", "tempView3"]
 
for tempview in tempview_list:
  dbutils.notebook.exit(spark.sql(f"Select * from {tempview}"))

但它只是返回第一个tempView的模式。
帮帮忙吧。我是游戏公园的新手。
谢谢。

tkclm6bt

tkclm6bt1#

你不能直接把 Dataframe 作为参数传递或者退出 Dataframe 。只有字符串可以这样传递。--你最终要做的就是退出视图的模式。
您要做的是将您要在笔记本之间传递的DataFrame写入global_temp_view。
一旦完成了这些操作,就可以将temp_view的名称/位置作为参数传递,或者将其退出到父视图。
This explains it best here (use example 1: https://docs.databricks.com/notebooks/notebook-workflows.html#pass-structured-data
然而,由于这只提供了退出一个 Dataframe /temp_view的指导,我将详细说明您提供的示例。
主要变化如下:

  • 退出的是视图名称而不是数据本身。
  • 您只能退出一个项目,因此将所有名称作为一个项目退出。
  • For循环位于父级中,用于使用名称从临时视图中读取。

在父节点中运行子笔记本,并将其output/exit赋值给一个变量:

child_output = dbutils.notebook.run(<notebookpath>, timeout, <arguments>)

儿童:

tempview_list = ["tempView1", "tempView2", "tempView3"]
dbutils.notebook.exit(tempview_list)

数组将作为字符串退出到child_output变量中:

"['tempView1', 'tempView2', 'tempView3']"

因此,在父对象中,您需要使用exec()将字符串重新转换为数组:

exec(f'tempview_list = {child_output}')

现在你已经完成了这个步骤,你可以在父笔记本中执行for循环了:

global_temp_db = spark.conf.get("spark.sql.globalTempDatabase")

for tempview in tempview_list:
  exec(f'{tempview}_df = table(global_temp_db + "." + tempview)')

这将基于您的temp_views生成3个 Dataframe :tempView1_df、tempView2_df和tempView3_df,您可以对它们执行任何操作。
我假设您已经从初始 Dataframe 创建了temp_views,您需要将这些视图更新为global_temp_views。

o4tp2gmn

o4tp2gmn2#

我建议您创建temporaryGlobalviews,您可以从工作流中的下一个/父笔记本加载它。
它不是那么优雅,但它的工作作为一个魅力。

mspsb9vt

mspsb9vt3#

我也遇到了同样的问题。一个非常有效的方法是在第一个笔记本中创建一个GlobalTempView,并在第二个笔记本中阅读它:
在第一个笔记本的末尾,您可以将 Dataframe 存储为GlobalTempView:

df_notebook1.createOrReplaceGlobalTempView('dataframe_temp_view')

并在接下来的笔记本中这样读:

df_temp = spark.table('dataframe_temp_view')
  • 只需确保两台笔记本电脑连接到同一群集

相关问题