3

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

CurrentCreditLines
0   5.0
1   14.0
2   NaN
3   5.0
4   19.0

有 110k 条记录,我如何计算移动平均线?我还需要将它舍入并使用浮点类型,我尝试了这个:

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

但我得到了错误:

'Series' object has no attribute 'float'
4

3 回答 3

2

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

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

test["CurrentCreditLines"].astype(float)
于 2021-12-05T09:09:48.783 回答
2

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

(
    test["CurrentCreditLines"]
    .rolling(min_periods=1, center=True, window=12)
    .mean()
    .round()
    .astype(float)
) 
于 2021-12-05T09:16:56.727 回答
1

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

也就是说,您的列看起来已经是浮点类型,因此执行转换是没有用的。

赶紧跑:

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

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

test["CurrentCreditLines"].astype(float).rolling(min_periods=1, center=True, window=12).mean()
于 2021-12-05T09:21:25.550 回答