python - Pandas 矢量化 - 在另一个 DataFrame 中查找最近的 future 时间

标签 python pandas vectorization

假设我有两个 pandas 时间序列数据帧:

a = pd.DataFrame([1,2,3,4,5,6,7,8,9],index=pd.date_range('2020-01-01', periods=9, freq='10min'))
b = pd.DataFrame(['a','b','c'],index=pd.date_range('2020-01-01', periods=3, freq='30min'))

有没有办法使用 pandas 对以下算法进行矢量化?

next_b = []
for row in a.itertuples():
    df = b[b.index >= row.Index]
    if len(df.index):
        next_b.append(df.index[0])
    else:
        next_b.append(None)    
a['next_b'] = next_b

输出:

                    0   next_b
2020-01-01 00:00:00 1   2020-01-01 00:00:00
2020-01-01 00:10:00 2   2020-01-01 00:30:00
2020-01-01 00:20:00 3   2020-01-01 00:30:00
2020-01-01 00:30:00 4   2020-01-01 00:30:00
2020-01-01 00:40:00 5   2020-01-01 01:00:00
2020-01-01 00:50:00 6   2020-01-01 01:00:00
2020-01-01 01:00:00 7   2020-01-01 01:00:00
2020-01-01 01:10:00 8   NaT
2020-01-01 01:20:00 9   NaT

最佳答案

merge_asof ,你可以这样做

res = pd.merge_asof(a, b.assign(next_b=b.index), 
                    left_index=True, right_index=True, 
                    direction='forward', suffixes=('','_b'))
print(res)
#                      0  0_b              next_b
# 2020-01-01 00:00:00  1    a 2020-01-01 00:00:00
# 2020-01-01 00:10:00  2    b 2020-01-01 00:30:00
# 2020-01-01 00:20:00  3    b 2020-01-01 00:30:00
# 2020-01-01 00:30:00  4    b 2020-01-01 00:30:00
# 2020-01-01 00:40:00  5    c 2020-01-01 01:00:00
# 2020-01-01 00:50:00  6    c 2020-01-01 01:00:00
# 2020-01-01 01:00:00  7    c 2020-01-01 01:00:00
# 2020-01-01 01:10:00  8  NaN                 NaT
# 2020-01-01 01:20:00  9  NaN                 NaT

关于python - Pandas 矢量化 - 在另一个 DataFrame 中查找最近的 future 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70040610/

相关文章:

python - 有什么方法可以根据 Pandas 中的特定条件在数据框的所有行中添加列名?

python - 加快深度的 numpy 整数数组索引

python - dict 不引用元素? Python2.7 改变了行为

python - python 中的 R data.chisq$residuals 等价于什么?

python - 在 lxml.html 元素的文本中搜索特殊 HTML 字符

python - 将 Nans 放在不在每一行的开始/结束数字内的列中

python - Pandas 根据两个条件设置列值

python - 减去 numpy diff 中的第一个和最后一个元素(环绕)

python - numpy ufunc/算术性能 - 整数不使用 SSE?

python - Numpy:对多个数组进行花式索引