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

如何在DataFrame中计算移动平均,解决Series无float属性报错问题

问题原因

你的代码报错是因为Pandas Series对象没有float属性,直接调用.float()属于非法语法。要将序列转为指定类型,需要使用Pandas提供的astype()方法指定目标数据类型。

正确实现代码

# 计算12期中心移动平均,四舍五入后转为float类型
result = test["CurrentCreditLines"].rolling(
    min_periods=1, 
    center=True, 
    window=12
).mean().round().astype("float")

补充说明

  • 如果你需要保留原始DataFrame的结构,想把计算结果作为新列存入原表,可以写为:
    test["CurrentCreditLines_rolling_mean"] = test["CurrentCreditLines"].rolling(
        min_periods=1, 
        center=True, 
        window=12
    ).mean().round().astype("float")
    
  • round()默认四舍五入保留0位小数,如果需要调整小数保留位数,可以传入参数,比如round(2)就是保留2位小数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:24:01