Skip to main content
 首页 » 编程设计

python之如何在 Python Pandas 中的数据流之间切换

2024年11月01日8zdz8207

我有两个数据流,都是一系列(时间戳,值)元组。 即:

[(2013-04-03T22:16:36+0000, 2334.5), (2013-04-03T22:46:36+0000, 43543.23), ...]   

我的想法是,其中一个将是“首选”,另一个不是,我想创建一个单一的时间序列,该时间序列是可用时较高优先级流的结果,而当不可用时则回退到最不受欢迎的流。

我的想法是将来自两个流的值的时间戳放入桶中,并将桶用作 DataFrame 的索引,每个流都有一个列,每个桶中有一个(时间戳,值)元组列表。然后我可以只遍历每个桶,例如选择点数最高的那个。

数据框看起来像这样:

timestamp            stream1                                  stream2   
2013-04-03 00:00:00  [(2013-04-03T00:16:36+0000, 2334.5),     [(2013-04-03T00:17:36+0000, 2314.5)] 
                      (2013-04-03T00:17:36+0000, 2314.5)] 
2013-04-03 00:30:00  [(2013-04-03T00:43:44+0000, 43543.23),   [(2013-04-03T00:47:36+0000, 2364.5)]  
                      (2013-04-03T00:54:24+0000, 4443.23)] 
2013-04-03 01:00:00  []                                       [(2013-04-03T01:01:30+0000, 34.34)] 
2013-04-03 01:30:00  [(2013-04-03T01:35:32+0000, 238734.3)]   [(2013-04-03T01:45:32+0000, 238734.3)] 

在这种情况下,时间戳已放入半小时桶中,stream1 是首选流。对于 00:00 的桶,将选择 stream1 中的两个点,对于 00:30 的桶,将选择流 1 中的两个点,对于 01:00 的桶,将选择 stream2 中的单个点作为stream1 没有数据,对于 01:30 的桶,将选择 stream1 中的单个数据点,因为它是首选流。

我该怎么做呢?我尝试创建数据框并使用 resample('h', how='count') 拆分为每小时计数,并使用 groupby,但不能完全将时间戳放入桶中,并为每个桶的每个流创建值列表。

请您参考如下方法:

我有一个解决方案,但我不确定它的效率如何(我自己是 Pandas 菜鸟),或者是否有更“ Pandas 风格”的方法:

hh = date_range('2013-01-01T00:30:00', periods=48, freq='1800S') 
s5 = date_range('2013-01-01', freq='5S', end='2013-01-02') 
s5 = s5[:720] + s5[1440:]  # introduce a gap in the 5 second data 
hh_d = Series(hh.astype('int') / 10 ** 9, index=hh) 
s5_d = Series(s5.astype('int') / 10 ** 9, index=s5) 
df = DataFrame({ 
    'hh': hh_d, 
    '5s': s5_d, 
}) 
# Make a grouping, for simplicity by day, hour 
grp = df.groupby(lambda x: (x.day, x.hour)) 
 
result = TimeSeries() 
for name, group in grp: 
    winner = None 
    for column in group.keys():  # iterate over the columns (streams) 
        data = group[column].dropna()  # ditch any NaNs that will be present 
        # next, perform the test (in this case, just the length) 
        if not winner or len(data) > len(group[winner].dropna()): 
            winner = column 
    # finally, add the data to the result set. 
    result = result.append(group[winner].dropna()) 

检查 5 秒间隔时的结果:

ipdb> result[719:725] 
2013-01-01 00:59:55    1357001995 
2013-01-01 01:00:00    1357002000 
2013-01-01 01:30:00    1357003800 
2013-01-01 02:00:00    1357005600 
2013-01-01 02:00:05    1357005605 
2013-01-01 02:00:10    1357005610 
dtype: float64 

这表明在间隙选择了半小时流。

上面的示例基于组中每列的长度,但我想可以应用任何测试。

希望有更多 pandas 经验的人可以详细说明我的稻草人答案!