Marco Nashaat
Marco Nashaat

Reputation: 67

how to calculate a moving average in a dataframe?

I have a dataframe column that looks like this:

CurrentCreditLines
0   5.0
1   14.0
2   NaN
3   5.0
4   19.0

with 110k records, how can I calculate the moving average? also I need it to be rounded and with type float, I tried this:

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

but I got the error:

'Series' object has no attribute 'float'

Upvotes: 2

Views: 155

Answers (3)

mozway
mozway

Reputation: 260630

As noted, float is not a valid pandas method.

That said, your column looks like it is already of float type, so it is useless to perform a conversion.

Just run:

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

If, for some reason, the column is of another type, perform the conversion before applying the rolling mean:

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

Upvotes: 1

Chiel
Chiel

Reputation: 2169

mrVerma is completely right. As a side note, when you chain so many operations it is sometime really handy to use brackets for readability:

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

Upvotes: 1

iamakhilverma
iamakhilverma

Reputation: 596

The error you're getting is telling you that it's not an issue with your .rolling() method but there is no .float() attribute of series in pandas, so, you should use pandas.DataFrame.astype() function to manipulate column dtypes.

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

test["CurrentCreditLines"].astype(float)

Upvotes: 2

Related Questions