python - 遍历 Pandas 中的 DateTimeIndex
问题描述
我有一个 Pandas DataFrame,其索引是一系列连续日期。我正在尝试遍历日期,但我被抛出一个 KeyError,我知道给定的密钥存在并且格式正确(Pandas Timestamp)
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')
在我看来,我正在输入我知道存在的精确密钥,但正在抛出 KeyError!我不确定问题出在哪里。任何帮助将不胜感激。
解决方案
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.
推荐阅读
- java - 以编程方式正确打开“设置”中的“关于设备”页面?
- sql - 如何计算内连接函数的结果
- python - 在 Django 中编辑验证错误
- angular - Angular 9:在构造函数运行之前检查组件模板
- c++ - std::sort() C++ 的自定义比较函数
- ruby-on-rails - ruby-on-rails 中的 Mongoid
- python - 熊猫“替换”方法无法替换点(。)字符
- flutter - Flutter Hero 动画不适用于 SliverAppBar
- unity3d - 如何在非运动学的刚体上使用动画?
- html - 设置垂直 li 导航菜单的样式,每个 li 都有图像和文本