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

Polars 0.20.5用Numpy类型转类型失败,与文档描述不符?

Polars 0.20.5中使用NumPy类型指定Schema/Series dtype报错的解决办法

问题重现

在Polars 0.20.5版本中,尝试用NumPy类型(如np.int64)定义LazyFrame的Schema或指定Series的数据类型时会触发报错:

1. LazyFrame Schema定义报错

代码示例:

import polars as pl
import numpy as np

data = {"a": [1.1, 2.2], "b": [3, 4]}
pl.LazyFrame(data, schema=[
    ('a', pl.Float32),
    ('b', np.int64)
])

报错信息:

ValueError: cannot infer dtype from <class 'numpy.int64'> (type: 'type')

2. Series dtype指定报错

代码示例:

import polars as pl
import numpy as np

series_2 = pl.Series('a', [1, 2], dtype=np.int64)

报错信息:

ValueError: given dtype: <class 'numpy.int64'> is not a valid Polars data type and cannot be converted into one

原因说明

Polars从0.20.x版本开始,不再直接支持将NumPy类型作为Schema或Series的dtype参数传入,尽管部分旧版文档仍保留相关说明,但实际API已调整,必须使用Polars自身提供的类型定义。

解决方法

将NumPy类型替换为对应的Polars内置类型即可:

1. 修正LazyFrame Schema

pl.LazyFrame(data, schema=[
    ('a', pl.Float32),
    ('b', pl.Int64)  # 替换np.int64为pl.Int64
])

2. 修正Series dtype

series_2 = pl.Series('a', [1, 2], dtype=pl.Int64)  # 替换np.int64为pl.Int64

常见NumPy类型与Polars类型的映射关系:

  • np.int64 → pl.Int64
  • np.int32 → pl.Int32
  • np.float32 → pl.Float32
  • np.float64 → pl.Float64
  • np.bool_ → pl.Boolean

内容的提问来源于stack exchange,提问作者J Piñol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:59:55