You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Databricks中Cursor执行的查询结果转换为Pandas DataFrame?

将Databricks SQL Cursor结果转换为Pandas DataFrame

要把Cursor返回的结果转成Pandas DataFrame,核心是要同时获取列名和数据行——因为fetchall()只返回纯数据元组,缺少字段名映射。以下是具体实现:

步骤说明

  • 导入pandas库
  • 从cursor.description中提取查询结果的列名(每个描述项的第一个元素就是列名)
  • 用fetchall()获取数据行,结合列名构造DataFrame

完整代码

from databricks import sql
import pandas as pd
import os

connection = sql.connect(
    server_hostname="hostname",
    http_path="http_path",
    access_token="token"
)
cursor = connection.cursor()

cursor.execute("SELECT * from schema.table limit 10")

# 提取列名
column_names = [desc[0] for desc in cursor.description]
# 获取数据并构造DataFrame
df = pd.DataFrame(cursor.fetchall(), columns=column_names)

# 验证结果
print(df.head())

cursor.close()
connection.close()

关键说明

  • cursor.description返回一个元组列表,每个元组包含对应列的名称、类型等元数据,取第一个元素desc[0]即可得到列名
  • pd.DataFrame()接受数据行列表和列名字段,直接生成结构化的DataFrame,方便后续分析操作

内容的提问来源于stack exchange,提问作者Xkid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:02:03