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

gannina
  • 173
  • 1
  • 8

2 Answers2

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
9769953
  • 10,344
  • 3
  • 26
  • 37
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

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

df['Vals',inplace=True]
smartass
  • 26
  • 4