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!

1

1 Answer 1

1

What about

df.fillna(method='ffill')
Sign up to request clarification or add additional context in comments.

6 Comments

Perhaps df.ffill()
Okay, I will do some investigations! Thank you!
@Bharath it is exactly the same see documentation
Yes, I know I meant you to add the short form as well
@xxyy are you trying to do on all the dataframe or on a given column?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.