熊猫进行多次序列连接与分组并扩展缺失数据

2024-09-30 01:21:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个从CSV文件导入的timeseries数据。 这些数据都有时间戳,但时间戳并不总是匹配的:

时间序列1:

                      UUT  Data
DateTime                                           
2017-11-21 18:54:31  uut1  1
2017-11-22 02:26:48  uut1  2
2017-11-22 10:19:44  uut1  3
2017-11-22 15:11:28  uut1  6
2017-11-22 23:21:58  uut1  7

时间序列2:

^{pr2}$

我可以使用concat函数将它们连接在一起并按“UUT”分组,但是,如何用前面的值填充空的时隙,使最终表看起来类似于:

DateTime          UUT   Data
11/21/17 18:47:29 uut1  1
11/21/17 18:54:31       1
11/22/17 2:26:48        2
11/22/17 2:26:49        2
11/22/17 10:19:44       3
11/22/17 15:11:28       6
11/22/17 15:17:47       6
11/22/17 23:21:58       7
11/23/17 7:10:56        8
11/23/17 15:15:48       8
11/23/17 15:22:16       9
11/24/17 12:16:58       11 
11/21/17 18:47:29 uut2  1
11/21/17 18:54:31       1
11/22/17 2:26:48        1
11/22/17 2:26:49        2
11/22/17 10:19:44       3
11/22/17 15:11:28       3
11/22/17 15:17:47       4
11/22/17 23:21:58       5
11/23/17 7:10:56        6
11/23/17 15:15:48       7
11/23/17 15:22:16       7
11/24/17 12:16:58       9

或者说:

DateTime            uut1 uut2
11/21/17 18:47:29   1   1
11/21/17 18:54:31   1   1
11/22/17 2:26:48    2   1
11/22/17 2:26:49    2   2
11/22/17 10:19:44   3   3
11/22/17 15:11:28   6   3
11/22/17 15:17:47   6   4
11/22/17 23:21:58   7   5
11/23/17 7:10:56    8   6
11/23/17 15:15:48   8   7
11/23/17 15:22:16   9   7
11/24/17 12:16:58   11  9

我的最终目标是能够在一个timeseries图上同时绘制uut1和uut2数据。在


Tags: 文件csv数据函数datadatetime时间序列
1条回答
网友
1楼 · 发布于 2024-09-30 01:21:20

找到索引与index.unionreindex数据帧,concat,然后pivot的并集,以获得所需的输出。在

i = df1.index.union(df2.index)
df1 = df1.reindex(i).reset_index().bfill().ffill()
df2 = df2.reindex(i).reset_index().bfill().ffill()

df = pd.concat([df1, df2]).pivot('DateTime', 'UUT', 'Data')
df

UUT                  uut1  uut2
DateTime                       
2017-11-21 18:47:29   1.0   1.0
2017-11-21 18:54:31   1.0   2.0
2017-11-22 02:26:48   2.0   2.0
2017-11-22 02:26:49   2.0   2.0
2017-11-22 10:19:44   3.0   3.0
2017-11-22 15:11:28   6.0   4.0
2017-11-22 15:17:47   6.0   4.0
2017-11-22 23:21:58   7.0   5.0
2017-11-23 07:10:56   7.0   6.0
2017-11-23 15:15:48   7.0   7.0
2017-11-24 12:16:58   7.0   9.0

最后,使用df.plot-

^{pr2}$

enter image description here

相关问题 更多 >

    热门问题