繁体   English   中英

在 pandas 中找到最接近日期时间值的最佳方法是什么?

[英]What's best way to find closest values of datetime in pandas?

import pandas as pd
import numpy as np
date1 = ['2020-01-01', '2019-01-01', '2018-01-01', '2017-01-01']
date2 = ['2020-03-01', '2021-01-01', '2018-01-02']
df1 = pd.DataFrame(np.arange(12).reshape(4,3), columns=['a', 'b', 'c'], index=date1)
df1.index = pd.to_datetime(df1.index)
df2 = pd.DataFrame(['a', 'b', 'c'], columns=['col1'])
df2['date'] = pd.to_datetime(date2)
df2['col2'] = np.zeros(3)
for ind in df2.index:
    val = df2['col1'][ind]
    df2['col2'][ind] = df1.iloc[df1.index.get_loc(df2['date'][ind], method='nearest')][val]

我需要从 df1 column = df1['col1'] 分配 df2['col2'] 值和最接近 df2['date'] 中的值的索引更有效的方式。

我的朋友帮了我)merge_asof https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html是我需要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM