【问题标题】:merge and sample two pandas time series合并和采样两个 pandas 时间序列
【发布时间】:2017-01-05 20:45:15
【问题描述】:

我有两个时间序列。我想合并它们和asfreq(*, method='pad') 结果,限制在它们共同共享的时间范围内。

为了说明,假设我这样定义AB

import datetime as dt
import numpy as np
import pandas as pd

A = pd.Series(np.arange(4), index=pd.date_range(dt.datetime(2017,1,4,10,0,0), 
              periods=4, freq=dt.timedelta(seconds=10)))

B = pd.Series(np.arange(6), index=pd.date_range(dt.datetime(2017,1,4,10,0,7),
              periods=6, freq=dt.timedelta(seconds=3)))

所以它们看起来像:

# A
2017-01-04 10:00:00    0
2017-01-04 10:00:10    1
2017-01-04 10:00:20    2
2017-01-04 10:00:30    3

# B
2017-01-04 10:00:07    0
2017-01-04 10:00:10    1
2017-01-04 10:00:13    2
2017-01-04 10:00:16    3
2017-01-04 10:00:19    4
2017-01-04 10:00:22    5

我想计算如下:

# combine_and_asfreq(A, B, dt.timedelta(seconds=5))
# timestamp            A   B
2017-01-04 10:00:07    0   0
2017-01-04 10:00:12    1   1
2017-01-04 10:00:17    1   3
2017-01-04 10:00:22    2   5

我该怎么做?

【问题讨论】:

  • 你可以看看函数merge_asof。我认为这就是应该做的。如果这不起作用,您可以进行外部连接,重新采样,然后删除剩余的 nan 值。 pandas.pydata.org/pandas-docs/stable/generated/…
  • 您是如何获得最终数据框中的时间的。为什么它们间隔 5 秒?
  • @TedPetrou 刚刚编辑了帖子以包含一个带有 timedelta(seconds=5) 参数的函数调用。

标签: python pandas


【解决方案1】:

我不确定您要问什么,但这里有一个有点复杂的方法,它首先找到重叠时间并创建一个单列数据帧作为具有 5 秒时间增量的“基础”数据帧。

通过正确设置数据框开始

start = max(A.index.min(), B.index.min())
end = min(A.index.max(), B.index.max())

df_time = pd.DataFrame({'time': pd.date_range(start,end,freq='5s')})

df_A = A.reset_index()
df_B = B.reset_index()

df_A.columns = ['time', 'value']
df_B.columns = ['time', 'value']

现在我们有以下三个数据框。

df_A

                 time  value
0 2017-01-04 10:00:00      0
1 2017-01-04 10:00:10      1
2 2017-01-04 10:00:20      2
3 2017-01-04 10:00:30      3

df_B

                time  value
0 2017-01-04 10:00:07      0
1 2017-01-04 10:00:10      1
2 2017-01-04 10:00:13      2
3 2017-01-04 10:00:16      3
4 2017-01-04 10:00:19      4
5 2017-01-04 10:00:22      5

df_time

                 time
0 2017-01-04 10:00:07
1 2017-01-04 10:00:12
2 2017-01-04 10:00:17
3 2017-01-04 10:00:22

使用 merge_asof 加入所有三个

pd.merge_asof(pd.merge_asof(df_time, df_A, on='time'), df_B, on='time', suffixes=('_A', '_B'))


                 time  value_A  value_B
0 2017-01-04 10:00:07        0        0
1 2017-01-04 10:00:12        1        1
2 2017-01-04 10:00:17        1        3
3 2017-01-04 10:00:22        2        5

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2021-04-07
    • 2016-10-03
    • 2017-06-03
    • 2018-07-03
    • 2015-11-07
    相关资源
    最近更新 更多