【问题标题】:Select Pandas dataframe rows based on 'hour' datetime根据“小时”日期时间选择 Pandas 数据框行
【发布时间】:2019-07-14 11:15:09
【问题描述】:

我有一个带有 datetime.time 类型的列“DateTimes”的 pandas 数据框“df”。

该列的条目是一天中的几个小时:

00:00:00
.
.
.
23:59:00

秒被跳过,以分钟为单位。

如何按小时选择行,例如 00:00:00 和 00:01:00 之间的行?


如果我试试这个:

df.between_time('00:00:00', '00:00:10')

我收到一个错误,即索引必须是 DateTimeIndex。

我这样设置索引:

df=df.set_index(keys='DateTime')

但我得到同样的错误。

我似乎也无法让 'loc' 工作。有什么建议吗?

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    这是您尝试做的工作示例:

    times = pd.date_range('3/6/2012 00:00', periods=100, freq='S', tz='UTC')
    df = pd.DataFrame(np.random.randint(10, size=(100,1)), index=times)
    df.between_time('00:00:00', '00:00:30')
    

    注意索引必须是 DatetimeIndex 类型。

    我了解您的日期/时间有一个专栏。问题可能是您的列不是这种类型,因此您必须先转换它,然后再将其设置为索引:

    # Method A
    df.set_index(pd.to_datetime(df['column_name'], drop=True)
    
    # Method B
    df.index = pd.to_datetime(df['column_name'])
    df = df.drop('col', axis=1)
    

    (只有在设置为索引后要删除原始列时才需要删除)

    【讨论】:

    • 谢谢,效果很好,因为我已经转换为 datetime.time 我在转换回 datetime 时遇到了问题,但我解决了。
    【解决方案2】:

    查看以下链接:
    将列转换为日期类型:Convert DataFrame column type from string to datetime
    按日期过滤数据框:Filtering Pandas DataFrames on dates
    希望对你有帮助

    【讨论】:

    • 谢谢,我的数据已经转换为日期时间,特别是 datetime.time。我已经阅读了第二个链接,但是他们对“loc”所做的事情在我的情况下似乎不起作用,而且讨论主要围绕日期,而不是时间,我很难从他们所说的与我的上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2020-04-29
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多