如何计算数据框中的移动平均线?

how to calculate a moving average in a dataframe?

我有一个如下所示的数据框列:

CurrentCreditLines
0   5.0
1   14.0
2   NaN
3   5.0
4   19.0

有 110k 条记录,如何计算移动平均线?我还需要它是四舍五入的,类型是 float,我试过这个:

test["CurrentCreditLines"].rolling(min_periods=1, center=True, window=12).mean().round().float()

但我得到了错误:

'Series' object has no attribute 'float'

您遇到的错误告诉您这不是您的 .rolling() 方法的问题,但 pandas 中没有 .float() 系列属性,因此,您应该使用 pandas.DataFrame.astype() 函数来操作列数据类型。

test["CurrentCreditLines"].rolling(min_periods=1, center=True, window=12).mean().round()

test["CurrentCreditLines"].astype(float)

mrVerma 完全正确。作为旁注,当您链接如此多的操作时,有时使用括号提高可读性真的很方便:

(
    test["CurrentCreditLines"]
    .rolling(min_periods=1, center=True, window=12)
    .mean()
    .round()
    .astype(float)
) 

如前所述,float 不是有效的 pandas 方法。

也就是说,你的列看起来已经是float类型了,再转换也没用。

就运行:

test["CurrentCreditLines"].rolling(min_periods=1, center=True, window=12).mean()

如果由于某种原因该列属于另一种类型,请在应用滚动平均值之前执行转换:

test["CurrentCreditLines"].astype(float).rolling(min_periods=1, center=True, window=12).mean()