I have this df:
JavaScript
x
13
13
1
Week U.S. 30 yr FRM U.S. 15 yr FRM
2
0 2014-12-31 3.87 3.15
3
1 2015-01-01 NaN NaN
4
2 2015-01-02 NaN NaN
5
3 2015-01-03 NaN NaN
6
4 2015-01-04 NaN NaN
7
8
2769 2022-07-31 NaN NaN
9
2770 2022-08-01 NaN NaN
10
2771 2022-08-02 NaN NaN
11
2772 2022-08-03 NaN NaN
12
2773 2022-08-04 4.99 4.26
13
And when I try to run this interpolation:
pmms_df.interpolate(method = 'nearest', inplace = True)
I get ValueError: Invalid fill method. Expecting pad (ffill) or backfill (bfill). Got nearest
I read in this post that pandas interpolate
doesn’t do well with the time columns, so I tried this:
pmms_df[['U.S. 30 yr FRM', 'U.S. 15 yr FRM']].interpolate(method = 'nearest', inplace = True)
but the output is exactly the same as before the interpolation.
Advertisement
Answer
It may not work great with date columns, but it works well with a datetime index, which is probably what you should be using here:
JavaScript
1
18
18
1
df = df.set_index('Week')
2
df = df.interpolate(method='nearest')
3
print(df)
4
5
# Output:
6
U.S. 30 yr FRM U.S. 15 yr FRM
7
Week
8
2014-12-31 3.87 3.15
9
2015-01-01 3.87 3.15
10
2015-01-02 3.87 3.15
11
2015-01-03 3.87 3.15
12
2015-01-04 3.87 3.15
13
2022-07-31 4.99 4.26
14
2022-08-01 4.99 4.26
15
2022-08-02 4.99 4.26
16
2022-08-03 4.99 4.26
17
2022-08-04 4.99 4.26
18