【问题标题】:Pandas: apply values from one time series to preceding instances of anotherPandas:将一个时间序列的值应用于另一个时间序列的先前实例
【发布时间】:2016-07-09 09:05:07
【问题描述】:

我有两个时间序列(但作为 DataFrame,即多元序列),ts1ts2Ts1 有重复的时间,ts2 没有。对于ts2 中的给定值ts2[i],我想将该值应用于ts1 中在ts2[i] 之前但在ts2[i-1] 之后的实例。

这是一个示例(为简单起见,单变量):

ts1:
    t           v
0   2016-03-01  0.676188
1   2016-03-01  0.228074
2   2016-03-04  0.371788
3   2016-03-05  0.802350
4   2016-03-06  0.090599

ts2:
    t           v
0   2016-03-02  1
1   2016-03-05  2
2   2016-03-08  3

我正在寻找这个结果:

    t           v
0   2016-03-01  1
1   2016-03-01  1
2   2016-03-04  2
3   2016-03-05  2
4   2016-03-06  3

Pandas 加入和合并操作并不能完全实现我想要的。 This post 有点接近,但也不是我想要的。这似乎是一个非常基本的“时间加入”,所以我认为应该有一些开箱即用的方法来做到这一点?

为了排除关于 ts1 中重复时间的问题:实际上,还有另一列(比如 ID 列)可以区分这些时间。所以在现实中,ts1 可以说是有一个MultiIndex。我想使示例尽可能简单,而且 ts2 not 有那个 ID 列。我想完全基于时间应用值。

我正在使用 Python 2.7.x 和 Pandas 0.17.0。如有必要,我可能会升级后者。 提前致谢!

【问题讨论】:

    标签: python python-2.7 pandas time-series


    【解决方案1】:

    IIUC 那么这应该可以工作:

    In [49]:
    ts1['v'] = ts2.loc[np.searchsorted(ts2['t'], ts1['t']),'v'].values
    ts1
    
    Out[49]:
               t  v
    0 2016-03-01  1
    1 2016-03-01  1
    2 2016-03-04  2
    3 2016-03-05  2
    4 2016-03-06  3
    

    所以这在你的 2 日期时间系列上使用 np.searchsorted 来返回应该插入 ts1['t'] 值的索引,这将是索引位置,然后我们使用它来索引 ts2 并返回'v'列值,我们必须在这里使用.values,因为在返回值中有重复的索引,所以我们只想要没有索引的值:

    In [51]:
    ts2.loc[np.searchsorted(ts2['t'], ts1['t']),'v']
    
    Out[51]:
    0    1
    0    1
    1    2
    1    2
    2    3
    Name: v, dtype: int64
    

    您可以看到np.searchsorted 的输出返回了所需的索引值:

    In [50]:
    np.searchsorted(ts2['t'], ts1['t'])
    
    Out[50]:
    array([0, 0, 1, 1, 2], dtype=int64)
    

    这假设值已经排序并且已经datetime dtype,如果没有你可以做ts1['t'] = pd.to_datetime(ts1['t'])

    【讨论】:

    • 感谢您的快速答复!实际上很简单......我想出了这个解决方案:ts = ts1.merge(ts2, on='t', how='outer').sort_values(by='t') mask = np.logical_not(ts.v_x.isnull()) ts.fillna(method='bfill')[mask] 但是你的解决方案更优雅。
    • 我认为这符合您的要求,因为您正在专门寻找前一行,np.searchsorted 这样做,只要对值进行排序并对其进行矢量化,这样它就会很快
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2013-06-02
    • 2020-11-22
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多