基于下面的Pandas DataFrame,有时间(秒)&心率值。虽然"time"应该是连续的数字,但我们看到了一些缺失的值。(1,2,4,5,7,9,10等)在这种情况下,我应该使用pandas.DataFrame.interpolate来获得所需的结果吗?或者有其他实现它的好主意吗?请注意,原始数据来自API。我试着在网上寻找任何答案,但没有运气…
原始:
time heartrate
0 97
3 105
6 105
8 111
11 111
13 114
16 115
所需输出:
time heartrate
0 97
1 100
2 103
3 105
4 105
5 105
6 105
7 109
8 111
9 111
10 111
11 111
12 113
13 114
14 114
15 114
16 115
定义time
为索引,然后与pd.RangeIndex
重新索引得到连续值,并插入heartrate
:
idx = pd.RangeIndex(df.time.min(), df.time.max()+1, name='time')
out = df.set_index('time').reindex(idx)['heartrate']
.interpolate(method='linear')
.pipe(np.ceil)
.reset_index()
输出:
>>> out
time heartrate
0 0 97.0
1 1 100.0
2 2 103.0
3 3 105.0
4 4 105.0
5 5 105.0
6 6 105.0
7 7 108.0
8 8 111.0
9 9 111.0
10 10 111.0
11 11 111.0
12 12 113.0
13 13 114.0
14 14 115.0
15 15 115.0
16 16 115.0
结果不精确. 你必须调整插值方法来得到想要的结果,但原理是一样的。
您可以使用reindex
和interpolate
,并使用np.ceil
来限制数字:
(np.ceil(df.set_index('time')
.reindex(range(df['time'].max()+1))
.interpolate())
.reset_index()
)
输出:
time heartrate
0 0 97.0
1 1 100.0
2 2 103.0
3 3 105.0
4 4 105.0
5 5 105.0
6 6 105.0
7 7 108.0
8 8 111.0
9 9 111.0
10 10 111.0
11 11 111.0
12 12 113.0
13 13 114.0
14 14 115.0
15 15 115.0
16 16 115.0