KO 的日线放得进一个 6,699 行的 DataFrame。想问“成交量最大的是哪一天?”,可以用 pandas 排序,也可以就地用 SQL 来问,不用启动数据库服务器,也不用加载任何东西。这就是 DuckDB:一个住在你 Python 进程里的数据库。
用通俗的话说这个想法
我们在哪里。 这是 DuckDB 技能的第一个主题。它假定你已掌握 SQL 技能的基础(选取、过滤、分组),并在 Python 中使用它们。下一个主题让 DuckDB 直接面向文件而不是 DataFrame。
定义进程内数据库
作为库运行在你自己程序内部、而不是作为独立服务器的数据库引擎。无需安装、启动或经网络连接,并且能直接读取程序自身的内存。
按名字查询 DataFrame
当 SQL 语句引用了一个不存在的表时,DuckDB 会查找同名的 Python 变量,如果它是 DataFrame(或 Arrow 表、Polars 帧),就直接读取。这叫 replacement scan。不会先把任何东西复制进数据库。
# DuckDB finds the variable called frame and queries it where it sitsframe = load_frame("KO")print(duckdb.sql("SELECT count(*) AS days, min(date) AS first_day, max(date) AS last_day FROM frame"))1
┌───────┬────────────┬────────────┐ │ days │ first_day │ last_day │ │ int64 │ date │ date │ ├───────┼────────────┼────────────┤ │ 6699 │ 2000-01-03 │ 2026-08-21 │ └───────┴────────────┴────────────┘
- 1
frame是 Python 变量,不是谁建的表。
连接、表和两种运行方式
duckdb.connect() 会打开一个自己的数据库,除非给出文件名,否则放在内存里。在那里建的表属于该连接。有两种调用执行 SQL。con.sql(查询) 返回一个惰性的关系对象,可以查看(.columns),并用 .fetchall()、.df() 或 .to_arrow_table() 收尾。con.execute(查询) 立刻执行,并在连接上留下一个游标,在这个连接上做别的事之前,必须用 fetchall() 把它读完。
# Copy the DataFrame into a table of this connection, then ask for a lazy relationprint(frame_to_table(con, "ko", frame))rel = con.sql("SELECT date, close FROM ko ORDER BY date DESC LIMIT 3")print(rel.columns)print(rel.fetchall())
6699 ['date', 'close'] [(datetime.date(2026, 8, 21), 91.1), (datetime.date(2026, 8, 20), 90.5), (datetime.date(2026, 8, 19), 90.35)]
# The same result in four shapesfor how in ("tuples", "dicts", "frame", "arrow"): result = rows_as(con, "SELECT date, close FROM ko ORDER BY date DESC LIMIT 2", how) print(how, "->", type(result).__name__)print(describe_table(con, "ko"))
tuples -> list
dicts -> list
frame -> DataFrame
arrow -> Table
[('date', 'DATE'), ('open', 'DOUBLE'), ('high', 'DOUBLE'), ('low', 'DOUBLE'), ('close', 'DOUBLE'), ('volume', 'BIGINT')]# An execute() cursor left unread blocks the next call on the same connectioncursor = con.execute("SELECT date FROM ko")cursor.fetchone()try: con.register("x", frame)except Exception as error: print(type(error).__name__)cursor.fetchall()con.register("x", frame)print("registered after reading the cursor to the end")
ResourceInUseException registered after reading the cursor to the end
把 execute() 的游标读完
fetchone() 只读一行并让游标保持打开,所以在该连接上的下一次调用会抛出提到未完成结果的错误。请用 fetchall(),或者用不占用连接的 con.sql(...)。用 fetchall()[0][0] 读取单个值是稳妥的习惯。
任务要求
- 1`frame_top_volume`对变量
frame写 SQL 查询,不要用 pandas 排序。 - 2`frame_to_table` 与 `describe_table`注册 DataFrame 并据此建表,再用
DESCRIBE读回各列。表名要经过ident()。 - 3`rows_as`一条查询,四种返回形态,其他情况给出清晰的错误。
快速检查
你的代码在同一个连接上先执行
con.execute(sql).fetchone(),再执行 con.register("x", frame),第二次调用抛出关于未完成结果的错误。怎么修复?请选择一个答案。
实验:评分内容
4 个任务 · 100 分- 就地查询 DataFrame:
frame_top_volume25 分 - 把 DataFrame 变成表:
frame_to_table25 分 - 一个结果,四种形态:
rows_as25 分 - 向数据库询问它自己:
describe_table25 分