我想使用插值函数,但只能在 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
我将一个数据集捆绑在一起,该数据集在“事件发生时”更新,但对每一列单独更新,并通过时间戳编制索引。这意味着经常有一些行没有记录某些列的数据,因此有很多 NaN!
最佳答案
我通过函数选择列的 min
和 max
值 idxmin和 idxmax并使用函数 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()
关于python - Pandas:列中第一个和最后一个数据点为 NaN 的插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33691591/