【问题标题】:Get TypeError: Index must be DatetimeIndex when filtering dataframe获取TypeError:过滤数据帧时索引必须是DatetimeIndex
【发布时间】:2017-10-05 02:10:05
【问题描述】:

我想通过特定的数据时间段过滤数据帧,如下面的代码。

df2 = df2['Dates'].between_time(pandas.to_datetime('5/13/2015 8:41'), pandas.to_datetime('5/13/2015 8:55'))[['Dates','Category']]

但出现错误“TypeError: Index must be DatetimeIndex” 这是数据框

enter image description here

我试过了

df2 = pandas.read_csv(path2,parse_dates=[0])

喜欢其他帖子的回复之一,但仍然遇到相同的错误。 有谁知道这里发生了什么?

【问题讨论】:

    标签: python pandas python-datetime


    【解决方案1】:

    如果您想按特定日期时间段过滤df,您可以尝试:

    start_date = pandas.to_datetime('5/13/2015 8:41')
    end_date = pandas.to_datetime('5/13/2015 8:55')
    df2.loc[(df2['Dates'] > start_date) & (df2['Dates'] < end_date)]
    

    【讨论】:

      【解决方案2】:

      正如你所提供的,我认为索引不是 DatetimeIndex,所以你可以尝试:

      df2.index=pd.to_datetime(df2.index)
      

      【讨论】:

        猜你喜欢
        • 2018-04-18
        • 2015-02-08
        • 2021-09-11
        • 2014-07-13
        • 1970-01-01
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        相关资源
        最近更新 更多