xxyy
xxyy

Reputation: 23

slow loop using panda

I am trying to replace each nan value in a series by the previous row's value. The data looks like:

16.5

NaN

16.5

NaN

NaN

16

NaN

Here is my code:

import pandas as pd
import numpy as np

df=pd.read_csv('test.csv')
AskPrice=df.AskPrice
for i, line in enumerate(AskPrice):
if np.isnan(line):
    AskPrice[i]=AskPrice[i-1]
print(AskPrice)

I want it to be:

16.5

16.5

16.5

16.5

16.5

16

16

I got the result but it took ages to complete the task. Is there a faster way? Thanks in advance!

Upvotes: 1

Views: 43

Answers (1)

rpanai
rpanai

Reputation: 13437

What about

df.fillna(method='ffill')

Upvotes: 1

Related Questions