【问题标题】:Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但获得了“Int64Index”实例
【发布时间】:2019-08-23 17:44:17
【问题描述】:

我正在尝试重新采样此 Dataframe 的 Timestamp 列:

  Transit.head():

      Timestamp                            Plate           Gate
  0 2013-11-01 21:02:17 4f5716dcd615f21f658229a8570483a8    65
  1 2013-11-01 16:12:39 0abba297ac142f63c604b3989d0ce980    64
  2 2013-11-01 11:06:10 faafae756ce1df66f34f80479d69411d    57

这就是我所做的:

  Transit.drop_duplicates(inplace=True)
  Transit.Timestamp = pd.to_datetime(Transit.Timestamp)
  Transit['Timestamp'].resample('1H').pad()

但我得到了这个错误:

  Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'

任何建议都会非常感激。

【问题讨论】:

    标签: python-3.x pandas datetime dataframe resampling


    【解决方案1】:

    DataFrame.set_index 创建DatetimeIndex - 上采样和下采样的解决方案:

    df = Transit.set_index('Timestamp').resample('1H').pad()
    print (df)
                                                    Plate  Gate
    Timestamp                                                  
    2013-11-01 11:00:00                               NaN   NaN
    2013-11-01 12:00:00  faafae756ce1df66f34f80479d69411d  57.0
    2013-11-01 13:00:00  faafae756ce1df66f34f80479d69411d  57.0
    2013-11-01 14:00:00  faafae756ce1df66f34f80479d69411d  57.0
    2013-11-01 15:00:00  faafae756ce1df66f34f80479d69411d  57.0
    2013-11-01 16:00:00  faafae756ce1df66f34f80479d69411d  57.0
    2013-11-01 17:00:00  0abba297ac142f63c604b3989d0ce980  64.0
    2013-11-01 18:00:00  0abba297ac142f63c604b3989d0ce980  64.0
    2013-11-01 19:00:00  0abba297ac142f63c604b3989d0ce980  64.0
    2013-11-01 20:00:00  0abba297ac142f63c604b3989d0ce980  64.0
    2013-11-01 21:00:00  0abba297ac142f63c604b3989d0ce980  64.0
    

    对于下采样是可能的使用参数on:

    df = Transit.resample('D', on='Timestamp').mean()
    print (df)
                Gate
    Timestamp       
    2013-11-01    62
    

    编辑:要删除所有重复的行 Timestamp 添加参数 subsetDataFrame.drop_duplicates

    Transit.drop_duplicates(subset=['Timestamp'], inplace=True)
    Transit.Timestamp = pd.to_datetime(Transit.Timestamp)
    df = Transit.set_index('Timestamp').resample('1H').pad()
    

    【讨论】:

    • 我已经尝试过了,这就是我得到的:无法使用方法或限制重新索引非唯一索引
    • @Dimi - 已编辑答案。
    • 确实,我尝试删除重复项的方式是错误的,这解决了我的问题。
    • @Dimi - 如果没有参数subset,如果通过检查所有列过滤掉重复,则只需指定一列。
    • 当我在我的情况下运行Transit.set_index('Timestamp').resample('D').sum() 时,输出类似于:2013-11-01T11:00:00.000000000 并且没有更多的列Timestamp
    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2015-08-31
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多