
本文详解如何将嵌套列表(list of lists)高效导入 polars dataframe,并指定列名与数据类型,避免默认列名(如 column_0)带来的混淆。
本文详解如何将嵌套列表(list of lists)高效导入 polars dataframe,并指定列名与数据类型,避免默认列名(如 column_0)带来的混淆。
Polars 对数据导入的语义比 Pandas 更严格,默认不自动推断行/列方向。当你传入 pl.DataFrame(numbers) 时,Polars 会尝试按列优先(column-wise) 解析——即把每个子列表视为一列,这显然不符合多数场景下“每行一个观测”的直觉。因此直接调用会报错或产生意外结构。
✅ 正确做法是显式指定 orient="row",明确告知 Polars:每个内层列表代表一行数据:
import polars as pl
numbers = [
['304-144635', 0],
['123-091523', 7],
['305-144931', 12],
['623-101523', 16],
['305-145001', 22],
['623-111523', 27],
['9998-2603', 29]
]
# 方式1:使用 orient="row"(自动命名:column_0, column_1)
df = pl.DataFrame(numbers, orient="row")
print(df)输出:
shape: (7, 2) ┌──────────┬─────────┐ │ column_0 ┆ column_1 │ │ --- ┆ --- │ │ str ┆ i64 │ ╞══════════╪══════════╡ │ 304-144635 ┆ 0 │ │ 123-091523 ┆ 7 │ │ … ┆ … │ │ 9998-2603 ┆ 29 │ └──────────┴─────────┘
⚠️ 注意:orient="row" 会自动推断数据类型(如字符串、整数),但若需精确控制(例如将第二列设为 Int32 或第一列为 Categorical),推荐配合 schema 参数使用:
# 方式2:显式定义 schema(推荐用于生产环境)
df = pl.DataFrame(
numbers,
orient="row",
schema=["id", "score"] # 自定义列名
)
# 或更严格地指定类型:
# schema={"id": pl.String, "score": pl.Int32}
print(df)输出(带自定义列名):
shape: (7, 2) ┌──────────┬───────┐ │ id ┆ score │ │ --- ┆ --- │ │ str ┆ i64 │ ╞══════════╪═══════╡ │ 304-144635 ┆ 0 │ │ 123-091523 ┆ 7 │ │ … ┆ … │ │ 9998-2603 ┆ 29 │ └──────────┴───────┘
? 关键提醒:
-
orient="row"是处理 list-of-lists 的标准方式;orient="col"仅适用于每个子列表本身是一列数据(极少见); - Polars 默认列名为
column_0,column_1…,与 Pandas 的0,1不同,且不可通过columns=参数在无 schema 时覆盖(必须用schema); - 若列表中存在
None或混合类型,建议显式声明schema以避免类型推断失败; - 性能上,
orient="row"+schema是最安全、最可预测的组合,尤其适合 ETL 流程。
掌握这一模式,你就能稳定、高效地将原始嵌套列表转化为结构化 Polars DataFrame,迈出高性能数据分析的第一步。

















