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

为何Pandas rolling方法返回的Series与原Series数据类型不同?

为什么Pandas Series的rolling窗口方法不保留原数据类型?

当使用float32类型的Series调用rolling窗口的mean()方法时,返回结果的数据类型会自动转为float64,示例代码如下:

import numpy as np
import pandas as pd

x = pd.Series(np.ones(6), dtype='float32')
print(x.dtype, x.rolling(window=3).mean().dtype)

执行后输出:

float32 float64

原因解析

Pandas在实现rolling窗口计算时,默认会使用float64精度来执行内部运算。这是出于计算准确性的考虑:窗口类计算(比如均值、求和)涉及多次累加或数值运算,使用更高精度的float64可以有效避免float32带来的精度损失问题,尤其是在窗口较大或数据复杂度高的场景下。

解决方案

如果需要强制保留原Series的数据类型,可以通过以下方式实现:

  • 显式转换数据类型:计算完成后直接用astype()转回原类型
result = x.rolling(window=3).mean().astype(x.dtype)
print(result.dtype)  # 输出: float32
  • 自定义聚合函数控制精度:利用agg()结合numpy的指定精度计算函数,在运算过程中维持原精度
result = x.rolling(window=3).agg(lambda win: np.mean(win, dtype=x.dtype))
print(result.dtype)  # 输出: float32

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:00:56