Skip to content Skip to sidebar Skip to footer

Pandas Filling Missing Values Down Based On Row Above

I have a dataframe like the following: import pandas as pd data={'col1':[1,3,3,1,2,3,2,2, 1], 'col2':[np.nan, 1, np.nan, 1, np.nan, np.nan, np.nan, 2, np.nan]} df=pd.DataFrame(data

Solution 1:

You can use np.where by looking at where the forward-fill is equal to one, filling 1 where it's True, and falling back to the value of 'col2' when it's False:

df['col2'] = np.where(df['col2'].ffill() == 1, 1, df['col2'])

The resulting output:

   col1  col2
01NaN131.0231.0311.0421.0531.0621.0722.081NaN

Solution 2:

You can use the df.fillna function with forward padding like this:

df.fillna(method='pad')

   col1  col2
01   NaN
131.0231.0311.0421.0531.0621.0722.0812.0

Solution 3:

ffilled = df.col2.ffill()
df.assign(col3=df.col2.fillna(ffilled[ffilled == 1]))

Post a Comment for "Pandas Filling Missing Values Down Based On Row Above"