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

Polars中shift_and_fill方法日期类型超类型匹配异常问题

Polars中shift_and_fill类型不匹配问题排查

问题情况

两段代码目标一致:将time_start序列偏移window_size位,并用初始数据填充前0~window_size位,但第一段运行抛出异常,第二段正常执行。

第一段代码(触发异常)

date_to_fill = df['time_start'][0]
df['time_start'] = df['time_start'].shift_and_fill(window_size, date_to_fill)

第二段代码(正常执行)

df['time_start'] = df['time_start'].shift(window_size)
df['time_start'].fill_null("backward")

抛出的异常信息

exceptions.ComputeError: Failed to determine supertype of Datetime(Nanoseconds, Some("UTC")) and Datetime(Microseconds, None)

测试数据

[{'time_start': datetime.datetime(2022, 7, 25, 10, 43, 52),
  'time_end': datetime.datetime(2022, 7, 25, 10, 43, 7),
  'value': None,
  'min_value': 80,
  'max_value': 98,
  'avg_value': 88.66666666666667},
 {'time_start': datetime.datetime(2022, 7, 25, 10, 43, 49),
  'time_end': datetime.datetime(2022, 7, 25, 10, 43, 2),
  'value': 79,
  'min_value': 79,
  'max_value': 80,
  'avg_value': 82.33333333333333},
 {'time_start': datetime.datetime(2022, 7, 25, 10, 43, 21),
  'time_end': datetime.datetime(2022, 7, 25, 10, 43),
  'value': 79,
  'min_value': 79,
  'max_value': 80,
  'avg_value': 79.33333333333333}]

使用Polars版本:0.13.58

原因分析

  • 第一段代码中,df['time_start'][0]取出的是Python原生datetime.datetime对象,传入shift_and_fill时会被Polars默认转为微秒级、无时区的Datetime类型。
  • 而DataFrame内的time_start列是纳秒级、带UTC时区的Polars Datetime类型,两者精度和时区不匹配,Polars无法找到兼容的共同类型,因此抛出异常。
  • 第二段代码的fill_null("backward")是在原列的类型基础上操作,全程沿用列本身的Datetime类型,不存在类型冲突。

解决方案

方案1:显式转换填充值的类型

先获取列的精度和时区元数据,将取出的初始值转换成和列一致的类型:

dtype = df['time_start'].dtype
date_to_fill = df['time_start'][0].astype(dtype)
df['time_start'] = df['time_start'].shift_and_fill(window_size, date_to_fill)

方案2:用Polars表达式引用初始值(更推荐)

直接用Polars表达式获取列的第一个值,避免Python原生类型的转换问题:

df = df.with_columns(
    pl.col('time_start').shift_and_fill(window_size, pl.col('time_start').first())
)

两种方案都能保证填充值的类型与列完全匹配,解决类型不兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:09:22