我有多个合并在一起的MultiIndex时间序列,索引是("location", "timestamp")。例子:
location timestamp x y z
A 1 1.2 4.3 NaN
A 2 2.2 5.3 NaN
A 3 NaN NaN 1.0
A 4 3.2 7.3 NaN
...
B 1 2.2 4.3 NaN
B 2 3.2 5.3 NaN
B 3 NaN NaN 2.0
B 4 5.2 7.3 NaN
...
"timestamp"是一个真正的日期时间列,为了简单起见,我在这里只是使用整数。我试图填补缺失的数据,所以每行有全套的数字。"x","y"one_answers"z"是平滑的,与其他数据系列无关,因此缺失的值可以垂直地线性导出,或者至少通过重复最后一个已知数字来导出。
我尝试了不同的groupby/ressample表达式,失败了。剩下的唯一一件事就是将所有东西分解成系列并对它们进行采样。一定有更好的方法
这里有几个方法可以做到
您可以ffill()
向前填充前一个值。
In [56]: df.ffill()
Out[56]:
location timestamp x y z
0 A 1 1.2 4.3 NaN
1 A 2 2.2 5.3 NaN
2 A 3 2.2 5.3 1
3 A 4 3.2 7.3 1
4 B 1 2.2 4.3 1
5 B 2 3.2 5.3 1
6 B 3 3.2 5.3 2
7 B 4 5.2 7.3 2
然而,如果某物以NaN
开头,它会保持不变。所以fillna(0)
为0
In [57]: df.ffill().fillna(0)
Out[57]:
location timestamp x y z
0 A 1 1.2 4.3 0
1 A 2 2.2 5.3 0
2 A 3 2.2 5.3 1
3 A 4 3.2 7.3 1
4 B 1 2.2 4.3 1
5 B 2 3.2 5.3 1
6 B 3 3.2 5.3 2
7 B 4 5.2 7.3 2
除了ffill()
,您还可以使用pd.Series.interpolate
In [58]: df.apply(pd.Series.interpolate).fillna(0)
Out[58]:
location timestamp x y z
0 A 1 1.2 4.3 0.00
1 A 2 2.2 5.3 0.00
2 A 3 2.7 6.3 1.00
3 A 4 3.2 7.3 1.25
4 B 1 2.2 4.3 1.50
5 B 2 3.2 5.3 1.75
6 B 3 4.2 6.3 2.00
7 B 4 5.2 7.3 2.00
并且,你可以用bfill()
来代替fillna(0)
,而不是ffill()
In [59]: df.apply(pd.Series.interpolate).bfill()
Out[59]:
location timestamp x y z
0 A 1 1.2 4.3 1.00
1 A 2 2.2 5.3 1.00
2 A 3 2.7 6.3 1.00
3 A 4 3.2 7.3 1.25
4 B 1 2.2 4.3 1.50
5 B 2 3.2 5.3 1.75
6 B 3 4.2 6.3 2.00
7 B 4 5.2 7.3 2.00