python - pandas.merge : match the nearest time stamp >= the series of timestamps

标签 python pandas

我有两个数据帧,它们都包含一个不规则间隔的毫秒分辨率时间戳列。我的目标是匹配行,以便对于每个匹配的行,1)第一个时间戳总是小于或等于第二个时间戳,以及 2)匹配的时间戳对于满足 1)的所有时间戳对是最接近的。

有没有办法用 pandas.merge 做到这一点?

最佳答案

merge()不能做这种join,但是可以使用searchsorted():

创建一些随机时间戳:t1t2,依次递增:

import pandas as pd
import numpy as np
np.random.seed(0)

base = np.array(["2013-01-01 00:00:00"], "datetime64[ns]")

a = (np.random.rand(30)*1000000*1000).astype(np.int64)*1000000
t1 = base + a
t1.sort()

b = (np.random.rand(10)*1000000*1000).astype(np.int64)*1000000
t2 = base + b
t2.sort()

调用 searchsorted()t2 中的每个值在 t1 中查找索引:

idx = np.searchsorted(t1, t2) - 1
mask = idx >= 0

df = pd.DataFrame({"t1":t1[idx][mask], "t2":t2[mask]})

这是输出:

                         t1                         t2
0 2013-01-02 06:49:13.287000 2013-01-03 16:29:15.612000
1 2013-01-05 16:33:07.211000 2013-01-05 21:42:30.332000
2 2013-01-07 04:47:24.561000 2013-01-07 04:53:53.948000
3 2013-01-07 14:26:03.376000 2013-01-07 17:01:35.722000
4 2013-01-07 14:26:03.376000 2013-01-07 18:22:13.996000
5 2013-01-07 14:26:03.376000 2013-01-07 18:33:55.497000
6 2013-01-08 02:24:54.113000 2013-01-08 12:23:40.299000
7 2013-01-08 21:39:49.366000 2013-01-09 14:03:53.689000
8 2013-01-11 08:06:36.638000 2013-01-11 13:09:08.078000

通过图表查看此结果:

import pylab as pl
pl.figure(figsize=(18, 4))
pl.vlines(pd.Series(t1), 0, 1, colors="g", lw=1)
pl.vlines(df.t1, 0.3, 0.7, colors="r", lw=2)
pl.vlines(df.t2, 0.3, 0.7, colors="b", lw=2)
pl.margins(0.02)

输出:

enter image description here

绿线是t1,蓝线是t2,红线是从t1中选出每个t2.

关于python - pandas.merge : match the nearest time stamp >= the series of timestamps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21201618/

相关文章:

python - 使用分组数据 reshape Pandas Dataframe(从长到宽)

python - 如何根据一列从 2 个数据帧中获取不匹配的数据。 ( Pandas )

python-3.x - Pandas 动态堆栈

python sdist recursive-include 文件夹,安装后在哪里?

Python 计数子串

即使安装了Python模块也找不到错误

python - 将元组列表列表转换为 MultiIndex pandas 数据框

python - 用于匹配重复出现的模式的正则表达式

python - Pandas:索引距已知标签一定位置的元素的惯用方法?

python - 将 float 分配给子集返回 1