简体   繁体   中英

Fill NaN values in dataframe with previous values in column

Hi I have a dataframe with some missing values ex:

在此处输入图片说明

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

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

有一个直接的同义词函数pandas.DataFrame.ffill

df['Vals',inplace=True]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM