5

Hi I have a dataframe with some missing values ex:

enter image description here

The black numbers 40 and 50 are the values already inputted and the red ones are to autofill from the previous values. Row 2 is blank as there is no previous number to fill.

Any idea how I can do this efficiently? I was trying loops but maybe there is a better way

3
  • 2
    Call fillna(method='bfill'). Commented Jul 30, 2018 at 7:51
  • 3
    Please dont post image of codes or dfs Commented Jul 30, 2018 at 7:52
  • Possible duplicate of How to replace NaNs by preceding values in pandas DataFrame? Commented Jul 30, 2018 at 8:04

2 Answers 2

9

It can be done easily with ffill method in pandas fillna.

To illustrate the working consider the following sample dataframe

df = pd.DataFrame()

df['Vals'] = [1, 2, 3, np.nan, np.nan, 6, 7, np.nan, 8]

    Vals
0   1.0
1   2.0
2   3.0
3   NaN
4   5.0
5   6.0
6   7.0
7   NaN
8   8.0

To fill the missing value do this

df['Vals'].fillna(method='ffill', inplace=True)

    Vals
0   1.0
1   2.0
2   3.0
3   3.0
4   3.0
5   6.0
6   7.0
7   7.0
8   8.0
Sign up to request clarification or add additional context in comments.

Comments

0

There is a direct synonym function for this, pandas.DataFrame.ffill

df['Vals',inplace=True]

Comments

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.