Pandas:列中第一个和最后一个数据点为 NaN 的插值

Pandas: interpolation where first and last data point in column is NaN

我想使用插值函数,但只能在 pandas DataFrame 列中的已知数据值之间使用。问题是列中的第一个和最后一个值通常是 NaN,有时在值不是 NaN 之前可能有很多行:

      col 1    col 2
 0    NaN      NaN
 1    NaN      NaN
...
1000   1       NaN
1001  NaN       1   <-----
1002   3       NaN  <----- only want to fill in these 'in between value' rows
1003   4        3
...
3999  NaN      NaN
4000  NaN      NaN

我正在将一个数据集捆绑在一起,该数据集已更新 'on event' 但每列单独更新,并通过时间戳编制索引。这意味着经常有一些行没有记录某些列的数据,因此有很多 NaN!

我 select 通过 minmax 列的值通过函数 idxmin and idxmax and use function fillna 使用前向填充方法。

print df
#      col 1  col 2
#0       NaN    NaN
#1       NaN    NaN
#1000      1    NaN
#1001    NaN      1
#1002      3    NaN
#1003      4      3
#3999    NaN    NaN
#4000    NaN    NaN

df.loc[df['col 1'].idxmin(): df['col 1'].idxmax()] = df.loc[df['col 1'].idxmin(): df['col 1'].idxmax()].fillna(method='ffill')
df.loc[df['col 2'].idxmin(): df['col 2'].idxmax()] = df.loc[df['col 2'].idxmin(): df['col 2'].idxmax()].fillna(method='ffill')
print df
#      col 1  col 2
#0       NaN    NaN
#1       NaN    NaN
#1000      1    NaN
#1001      1      1
#1002      3      1
#1003      4      3
#3999    NaN    NaN
#4000    NaN    NaN

添加了不同的解决方案,谢谢 HStro

df['col 1'].loc[df['col 1'].first_valid_index() : df['col 1'].last_valid_index()] = df['col 1'].loc[df['col 1'].first_valid_index(): df['col 1'].last_valid_index()].astype(float).interpolate()