Skip to content Skip to sidebar Skip to footer

Linearly Interpolate Missing Rows In Pandas Dataframe

I have the foll. dataframe: Value ts year JD check group_id 0 NaN 950832000 2000 49 NaN 19987 1

Solution 1:

You could convert your JD values to a DateTimeIndex and resample to daily frequency ((see docs). pandas.Series.interpolate() will then fill in the missing values between existing values in the Value columns as follows:

start = date(2000, 1, 1)
df.index = pd.DatetimeIndex(df.JD.apply(lambda x: start + relativedelta(days=int(x)-1)))
df = df.resample('D')
df.loc[:, ['Value', 'JD']] = df.loc[:, ['Value', 'JD']].interpolate(method='linear', limit_direction='both', limit=100)
df.tail(25)

               Value         ts  year   JD  check  group_id
2000-11-24  0.333167        NaN   NaN  329    NaN       NaN
2000-11-25  0.333620        NaN   NaN  330    NaN       NaN
2000-11-26  0.334074        NaN   NaN  331    NaN       NaN
2000-11-27  0.334527        NaN   NaN  332    NaN       NaN
2000-11-28  0.334980        NaN   NaN  333    NaN       NaN
2000-11-29  0.335434        NaN   NaN  334    NaN       NaN
2000-11-30  0.335887        NaN   NaN  335    NaN       NaN
2000-12-01  0.336341        NaN   NaN  336    NaN       NaN
2000-12-02  0.336794  975715200  2000  337      1     19987
2000-12-03  0.337247        NaN   NaN  338    NaN       NaN
2000-12-04  0.337701        NaN   NaN  339    NaN       NaN
2000-12-05  0.338154        NaN   NaN  340    NaN       NaN
2000-12-06  0.338608        NaN   NaN  341    NaN       NaN
2000-12-07  0.339061        NaN   NaN  342    NaN       NaN
2000-12-08  0.339514        NaN   NaN  343    NaN       NaN
2000-12-09  0.339968        NaN   NaN  344    NaN       NaN
2000-12-10  0.340421        NaN   NaN  345    NaN       NaN
2000-12-11  0.340875        NaN   NaN  346    NaN       NaN
2000-12-12  0.341328        NaN   NaN  347    NaN       NaN
2000-12-13  0.341782        NaN   NaN  348    NaN       NaN
2000-12-14  0.342235        NaN   NaN  349    NaN       NaN
2000-12-15  0.342688        NaN   NaN  350    NaN       NaN
2000-12-16  0.343142        NaN   NaN  351    NaN       NaN
2000-12-17  0.343595        NaN   NaN  352    NaN       NaN
2000-12-18  0.344049  977097600  2000  353      1     19987

You will notice that .interpolate() only backfills missing values at the beginning of the series, which is due to the scipy.interp1d behavior for bound_error as described [in the scipy docs].2


Post a Comment for "Linearly Interpolate Missing Rows In Pandas Dataframe"