【问题标题】:Rows from pandas dataframe between two time values两个时间值之间的 pandas 数据帧中的行
【发布时间】:2020-03-27 05:37:07
【问题描述】:

我有一个这样的熊猫数据框(时间戳转换为日期时间对象):

    id  timestamp
0   221 2020-11-07 12:02:00
1   223 2020-11-08 13:21:00
2   224 2020-11-09 12:50:00
3   225 2020-11-10 14:23:00
4   226 2020-11-11 12:25:00
5   227 2020-11-14 14:26:00

我想查找时间间隔之间的行数。例如 12:00-13:00,这里是 3(条目 0、2 和 4)

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

所以正如我评论的那样,我认为你可以使用between_time 函数:

CountRows = df.set_index('timestamp').between_time('12:00','13:00').shape[0]

在您的情况下,这会将列 timestamp 设置为索引,然后返回两个时间值之间的行数。其中:

"Dataframe.shape 返回的元组的第一个元素包含 数据框中索引中的项目数,即基本上是数字 数据框中的行数。 Source

【讨论】:

  • 如果您需要结果,只需删除 .shape[0]
【解决方案2】:

请尝试

将时间戳强制转换为日期时间并按升序排序

  df['timestamp']=pd.to_datetime(df['timestamp']).sort_values(ascending=True)

重置索引但不删除以保留id

df.reset_index(drop=False, inplace=True)

将时间戳设置为新索引以允许使用 df.between 时间

df.set_index(df['timestamp'], inplace=True)
df.between_time('12:00', '13:00')

【讨论】:

    【解决方案3】:

    由于我认为建议的between_time 仅适用于DatetimeIndex,因此您可以将DataFrame index 设置为'timestamp',然后使用between_time,或者,首先使用sorting

    df.sort_values(by='timestamp',axis='columns',inplace=True)
    

    然后使用sorted search

    start = df['timestamp'].searchsorted(pd.Timestamp('2020-11-07 12:00:00'), side='left')
    end = df['timestamp'].searchsorted(pd.Timestamp('2020-11-07 13:00:00'), side='right')
    

    然后求行数

    count = start - end
    

    【讨论】:

      【解决方案4】:

      正如评论部分中的帖子所建议的那样 between_time 效果很好。需要先将时间戳(这里是 datetime64 对象)作为索引,然后使用 between_time 函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        • 1970-01-01
        • 1970-01-01
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多