How do I interpolate filling in nans with the minimum value on either side?

Viewed 46

I have a dataframe of the form:

df = {'col_1': [5,4,np.nan,np.nan,1,0,1,2,np.nan,np.nan,5],
        'col_2': [5,4,3,2,np.nan,np.nan,np.nan,np.nan,3,4,5]}

df = pd.DataFrame(df)

I want to "interpolate" but taking the min value on either side for desired result of:

df_desired = {'col_1': [5,4,1,1,1,0,1,2,2,2,5],
        'col_2': [5,4,3,2,2,2,2,2,3,4,5]}

df_desired = pd.DataFrame(df_desired)

Does anyone know a good way of doing this? Thanks!

1 Answers

Here is a way where you can get np.miminum between ffill and bfill

out = np.minimum(df.ffill(),df.bfill())

print(out)

    col_1  col_2
0     5.0    5.0
1     4.0    4.0
2     1.0    3.0
3     1.0    2.0
4     1.0    2.0
5     0.0    2.0
6     1.0    2.0
7     2.0    2.0
8     2.0    3.0
9     2.0    4.0
10    5.0    5.0
Related