如何在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
相关产品推荐
相关产品推荐

