【发布时间】:2018-04-06 19:32:39
【问题描述】:
问题和我想要什么
我有一个数据文件,其中包含从多个传感器异步读取的时间序列。基本上,对于我文件中的每个数据元素,我都有一个传感器 ID 和读取它的时间,但我并不总是每次都有所有传感器,并且读取时间可能不均匀。比如:
ID,time,data
0,0,1
1,0,2
2,0,3
0,1,4
2,1,5 # skip some sensors for some time steps
0,2,6
2,2,7
2,3,8
1,5,9 # skip some time steps
2,5,10
重要提示实际的time 列是日期时间类型。
我想要的是能够在该传感器不存在的任何时间步长内为每个传感器保持零阶保持(前向填充)值,并将任何未读取的传感器设置为零或回填最早的时间步。我想要的是一个看起来像是从以下位置读取的数据框:
ID,time,data
0,0,1
1,0,2
2,0,3
0,1,4
1,1,2 # ID 1 hold value from time step 0
2,1,5
0,2,6
1,2,2 # ID 1 still holding
2,2,7
0,3,6 # ID 0 holding
1,3,2 # ID 1 still holding
2,3,8
0,5,6 # ID 0 still holding, can skip totally missing time steps
1,5,9 # ID 1 finally updates
2,5,10
迄今为止的熊猫尝试
我初始化我的数据框并设置我的索引:
df = pd.read_csv(filename, dtype=np.int)
df.set_index(['ID', 'time'], inplace=True)
我试图搞砸类似的事情:
filled = df.reindex(method='ffill')
或类似的将各种值传递给index 关键字参数,如df.index、['time'] 等。这总是会引发错误,因为我传递了无效的关键字参数,或者对数据框不可见。我认为它没有认识到我正在寻找的数据是“缺失的”。
我也试过了:
df.update(df.groupby(level=0).ffill())
或基于Multi-Indexed fillna in Pandas 的level=1,但我认为数据框没有任何可见的变化,我想是因为我目前没有任何我想要我的价值观去的地方。
到目前为止的 Numpy 尝试
我在使用 numpy 和非整数索引时遇到了一些运气,例如:
data = [np.array(df.loc[level].data) for level in df.index.levels[0]]
shapes = [arr.shape for arr in data]
print(shapes)
# [(3,), (2,), (5,)]
data = [np.array([arr[i] for i in np.linspace(0, arr.shape[0]-1, num=max(shapes)[0])]) for arr in data]
print([arr.shape for arr in data])
# [(5,), (5,), (5,)]
但这有两个问题:
- 它把我带出了熊猫世界,我现在必须手动维护我的传感器 ID、时间索引等以及我的特征向量(实际的
data列不仅仅是一列,而是大量的值来自传感器套件)。 - 考虑到列数和实际数据集的大小,在我的实际示例中实现这将是笨重且不优雅的。我更喜欢在熊猫中这样做。
应用程序
最终,这只是训练循环神经网络的数据清理步骤,对于每个时间步,我需要提供一个始终具有相同结构的特征向量(每个时间步的每个传感器 ID 的一组测量值)。
感谢您的帮助!
【问题讨论】:
标签: python pandas numpy multi-index reindex