Python 合并并采样两个时间序列

Python 合并并采样两个时间序列,python,pandas,Python,Pandas,我有两个时间序列。我想将它们合并到asfreq(*,method='pad')结果中,限制在它们共享的时间范围内 为了举例说明,假设我这样定义A和B: 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.

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

为了举例说明,假设我这样定义
A
B

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

我怎样才能做到这一点呢?

我不太清楚你在问什么,但这里有一个有点复杂的方法,首先找到重叠的时间,并创建一个单列数据帧作为带有5s时间增量的“基本”数据帧

通过正确设置数据帧开始 现在我们有以下三个数据帧

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
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连接所有三个
您可以查看函数merge\u asof。我想这就是它应该做的。如果这不起作用,可以进行外部连接、重新采样,然后删除剩余的nan值。您是如何在最终数据帧中获得时间的。为什么它们之间的间隔是5秒?@TedPetrou刚刚编辑了一篇文章,其中包含了一个带有
timedelta(seconds=5)
参数的函数调用。
                 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
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