I have a large 1D-array with some 'NaN' values dispersed in it. I would like to replace the 'NaN' values with the mean of the values on each side of the 'NaN'.
There is a lot of documentation on this site about replacing 'NaN' with the mean of a column or row, but I want to replace it with just the average of its neighbors.
I have written the following code, but it is not replacing the 'NaN' values at all. Can someone please tell me what I am doing wrong? Thanks in advance.
import numpy as np
lfc=['NaN', 4, 'NaN', 6, 3, 'NaN', 1]
for i in range(0, len(lfc)):
if lfc[0] == 'nan':
lfc[0] = lfc[1]
elif lfc[i] == 'nan':
lfc[i] = (lfc[i-1] + lfc[i+1]) / 2
elif lfc[len(lfc)-1] == 'nan':
lfc[len(lfc)-1] = lfc[len(lfc)-2]
Edit
Sample input:
lfc=['NaN', 4, 'NaN', 6, 3, 'NaN', 1]
Expected output:
lfc=[4, 4, 5, 3, 2, 1]