【问题标题】:Compare two dataframes and keep a specific datetime range of another比较两个数据框并保留另一个数据框的特定日期时间范围
【发布时间】:2020-04-29 08:17:20
【问题描述】:

我有两个带有时间戳的数据框。我想从df1 中选择等于df2 的时间戳'start_show' 的时间戳,但还要保留df1 2 小时前和2 小时后(df1)的所有时间戳,其中时间戳相等。

df1:

       van_timestamp         weekdag
2880    2016-11-19 00:00:00    6
2881    2016-11-19 00:15:00    6
2882    2016-11-19 00:30:00    6
...            ...            ...
822349  2019-11-06 22:45:00    3
822350  2019-11-06 23:00:00    3
822351  2019-11-06 23:15:00    3

df2:

            einde_show               start_show
255     2016-01-16 22:00:00      2016-01-16 20:00:00
256     2016-01-23 21:30:00      2016-01-23 19:45:00
257     2016-01-26 21:30:00      2016-01-26 19:45:00
...                ...                    ...
1111    2019-12-29 18:30:00      2019-12-29 17:00:00
1112    2019-12-30 15:00:00      2019-12-30 13:30:00
1113    2019-12-30 18:30:00      2019-12-30 17:00:00

df1 每天每 15 分钟包含一个时间戳,而df2['start_show'] 每天只包含一个时间戳。

所以最终我想要实现的是,对于df2 的每个时间戳,我都有df1 +- 2 小时的相应时间戳。

到目前为止我已经尝试过:

df1['van_timestamp'][df1['van_timestamp'].isin(df2['start_show'])]

这会选择正确的时间戳。现在我想从df1中选择

范围内的所有内容
+ pd.Timedelta(2, unit='h')
- pd.Timedelta(2, unit='h')

但我不知道该怎么做。非常感谢您的帮助!

谢谢!

【问题讨论】:

    标签: python pandas loops dataframe compare


    【解决方案1】:

    我让它工作了(丑陋的修复)。我创建了一个日期时间范围

    dates = [pd.date_range(start = df2['start_show'].iloc[i] - pd.Timedelta(2, unit='h'), end = df2['start_show'].iloc[i], freq = '15T') for i in range(len(evs_data))]
    

    然后我没有列出:

    dates = [i for sublist in dates for i in sublist]
    

    之后我将数据框与此列表进行了比较。

    relevant_timestamps = df1[df1['van_timestamp'].isin(dates)]
    

    如果其他人有更好的解决方案,请告诉我!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多