代码之家  ›  专栏  ›  技术社区  ›  cshadowstar

遍历Pandas中的DateTimeIndex

  •  1
  • cshadowstar  · 技术社区  · 7 年前

    import pandas as pd
    import datetime
    
    ## Importing the data from the Sep 2016-August 2018
    ## Step count & Date features only
    
    features = ['Date','Step count']
    data = pd.read_csv('fit_daily_sum_Sep2016_Aug2018.csv', sep=',', usecols=features).set_index('Date')
    # To convert data index to datetime
    data.index = pd.to_datetime(data.index)
    
    tmp = data.head()
    print tmp.index
    print 'first key',tmp.index[0]
    print type(tmp.index[0])
    
    fkey = pd.Timestamp(2016,9,2)
    print 'fkey is',fkey
    for x in xrange(0, len(tmp)):
        print 'running',fkey+datetime.timedelta(days=x)
        print tmp[fkey+datetime.timedelta(days=x)]
    

    最后一行的第一次迭代抛出一个KeyError。控制台显示如下(浓缩)

    DatetimeIndex(['2016-09-02', '2016-09-03', '2016-09-04', '2016-09-05',
               '2016-09-06'],
              dtype='datetime64[ns]', name=u'Date', freq=None)
    first key 2016-09-02 00:00:00
    <class 'pandas._libs.tslibs.timestamps.Timestamp'>
    fkey is 2016-09-02 00:00:00
    running 2016-09-02 00:00:00
    KeyError: Timestamp('2016-09-02 00:00:00')
    

    在我看来,我正在输入我知道存在的精确的密钥,但却抛出了一个密钥错误!我不确定问题出在哪里。任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Max    5 年前
    tmp[fkey+datetime.timedelta(days=x)]
    

    这部分是查看数据帧的列标题,而不是索引。

    尝试

    tmp.loc(fkey+datetime.timedelta(days=x))
    

    tmp['Step count'][fkey+datetime.timedelta(days=x)]
    #where 'Step count' is the column name of interest.