【问题标题】:How to remove rows where a datetime column matches interval condition如何删除日期时间列与间隔条件匹配的行
【发布时间】:2020-11-04 08:21:36
【问题描述】:

我正在下载延长时间(从美国东部标准时间凌晨 4 点到晚上 8 点)的市场盘中数据点。我需要摆脱每天延长的工作时间,只保留上午 9:30 到下午 4 点之间的条目。

数据样本:

time,...
2018-11-13 04:05,...
2018-11-13 07:05,...
2018-11-13 08:05,...
2018-11-13 09:00,...
2018-11-13 10:00,...
...
2018-11-13 15:00,...
2018-11-13 16:00,...
2018-11-13 17:00,...
2018-11-13 18:00,...
2018-11-13 19:00,...
2018-11-13 20:00,...

因此,对于“时间”列,我只需要保留大于 9:30 且小于 16:00(每天)的条目。

如何过滤掉?

谢谢

【问题讨论】:

标签: python pandas datetime


【解决方案1】:

您可以使用.between_time。如果您的数据框如下所示:

                time col
0   2018-11-13 04:05   a
1   2018-11-13 07:05   b
2   2018-11-13 08:05   c
3   2018-11-13 09:00   d
4   2018-11-13 10:00   e
5   2018-11-13 15:00   f
6   2018-11-13 16:00   g
7   2018-11-13 17:00   h
8   2018-11-13 18:00   i
9   2018-11-13 19:00   j
10  2018-11-13 20:00   k

然后:

df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')
print( df.between_time('09:30', '16:00') )

打印:

                    col
time                   
2018-11-13 10:00:00   e
2018-11-13 15:00:00   f
2018-11-13 16:00:00   g

【讨论】:

  • 准确。在此处查看文档:between time
  • 也许df.groupby(df.index.date).apply(lambda x: x.between_time('09:30','16:00')) 以防万一他需要找到多天的时间范围?
【解决方案2】:

其他用户here已经给出了这个问题的答案。

你必须使用df.between_time(from, to)。这是一个代码示例:

import pandas as pd
df = pd.read_csv(path_to_your_file) # or use another way to read / create dataframe
df.between_time('9:30', '16:00')

【讨论】:

    【解决方案3】:

    您可以从日期中获取时间,然后只需检查时间并使用 true 查询时间

    format = "%H:%M"
    df = df.loc[df['time'].dt.time>day.strftime("9:30", format) and df['time'].dt.time<day.strftime("16:00", format)]
    

    【讨论】:

      【解决方案4】:
      df['time'] = pd.to_datetime(df['time'])
      df.set_index('time', inplace=True)
      df.loc['2018-11-13 09:30':'2018-11-13 16:00']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        • 2015-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多