1

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!

xxyy
  • 23
  • 4
  • Possible duplicate of [How to replace NaNs by preceding values in pandas DataFrame?](https://stackoverflow.com/questions/27905295/how-to-replace-nans-by-preceding-values-in-pandas-dataframe) – Bharath M Shetty Dec 02 '17 at 10:31

1 Answers1

1

What about

df.fillna(method='ffill')
rpanai
  • 12,515
  • 2
  • 42
  • 64