python - 在多索引数据框中填充缺失的时间值

标签 python pandas numpy multi-index reindex

问题和我想要的

我有一个数据文件,其中包含从多个传感器异步读取的时间序列。基本上对于我文件中的每个数据元素,我都有一个传感器 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列是datetime类型。

我想要的是能够在传感器不存在的任何时间步长内为每个传感器零阶保持(前向填充)值,并设置为零或回填任何未读取的传感器最早的时间步骤。我想要的是一个看起来像是从以下位置读取的数据框:

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

到目前为止 Pandas 的尝试

我初始化我的数据框并设置我的索引:

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())

level=1 基于 Multi-Indexed fillna in Pandas ,但我再次没有看到数据框的明显变化,我想是因为我目前没有任何我希望我的值(value)观去的地方。

到目前为止的 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,)]

但这有两个问题:

  1. 这让我脱离了 pandas 世界,现在我必须手动维护我的传感器 ID、时间索引等以及我的特征向量(实际的 data 列不仅仅是一列但是来自传感器套件的大量值)。
  2. 考虑到实际数据集的列数和大小,在我的真实示例中实现起来会很笨重且不够优雅。我更喜欢用 pandas 做这件事的方式。

应用

最终,这只是训练递归神经网络的数据清理步骤,对于每个时间步,我需要提供一个始终具有相同结构的特征向量(每个时间步的每个传感器 ID 的一组测量值).

感谢您的帮助!

最佳答案

这是一种方法,使用 reindexcategory

df.time=df.time.astype('category',categories =[0,1,2,3,4,5])
new_df=df.groupby('time',as_index=False).apply(lambda x : x.set_index('ID').reindex([0,1,2])).reset_index()
new_df['data']=new_df.groupby('ID')['data'].ffill()
new_df.drop('time',1).rename(columns={'level_0':'time'})
Out[311]: 
    time  ID  data
0      0   0   1.0
1      0   1   2.0
2      0   2   3.0
3      1   0   4.0
4      1   1   2.0
5      1   2   5.0
6      2   0   6.0
7      2   1   2.0
8      2   2   7.0
9      3   0   6.0
10     3   1   2.0
11     3   2   8.0
12     4   0   6.0
13     4   1   2.0
14     4   2   8.0
15     5   0   6.0
16     5   1   9.0
17     5   2  10.0

关于python - 在多索引数据框中填充缺失的时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937010/

相关文章:

python - 如何根据第三轴上的所有值从numpy数组中获取掩码

python - 无法使用 3D 掩蔽和索引将值分配给 numpy 数组

python - 显示男性和女性 x 值的 Matplotlib 条形图

python - 没有 init 方法接受参数的类

python - 在两个 Pandas 数据框中查找公共(public)行(交集)

json - 从whattomine中的链接接收JSON数据而不抓取HTML

python - 如何从 Jupyter 笔记本上的 * .IPYNB 文件执行 * .PY 文件?

python - 更新 Combo 的默认值

python - Pandas :用列表分隔行的记录

python - torch.argmax() 无法在包含数据的张量中找到最大值