如何为时间序列创建日期索引?Python读取时列名识别报错
解决读取时间序列时的KeyError: 'stamp'问题
问题重现
尝试将读取的数据转为时间序列时触发KeyError: 'stamp',代码如下:
speedmat = pandas.read_pickle('../data/simulation_simple/speed_matrix_2015') timeserie = speedmat.T.iloc[:, 0:8064] timeserietimeserie["stamp"] = pd.to_datetime(timeserie["stamp"])
报错信息:
KeyError Traceback (most recent call last) ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 3628 try: -> 3629 return self._engine.get_loc(casted_key) 3630 except KeyError as err: ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'stamp'
解决方案
1. 修正变量名笔误
代码里timeserietimeserie是输入错误,应改为timeserie,但这只是语法问题,核心是当前timeserie中不存在名为stamp的列。
2. 确认数据结构
先运行以下代码查看timeserie的列和索引,定位时间戳的位置:
# 查看所有列名 print(timeserie.columns) # 查看索引内容 print(timeserie.index) # 查看数据前几行 print(timeserie.head())
3. 针对性处理
情况1:时间戳在索引中
转置(.T)会互换原始数据的行和列,若时间戳原本是speedmat的行索引,转置后会成为timeserie的列名;若原本是speedmat的列名,转置后会成为timeserie的行索引。对应处理方式:
- 时间戳是列名时:
# 将列名转为datetime类型 timeserie.columns = pd.to_datetime(timeserie.columns) # 可选:将列名转为单独的stamp列 timeserie = timeserie.reset_index().rename(columns={'index': 'stamp'}) timeserie['stamp'] = pd.to_datetime(timeserie['stamp'])
- 时间戳是行索引时:
# 将行索引转为datetime类型 timeserie.index = pd.to_datetime(timeserie.index) # 可选:转为单独的stamp列 timeserie['stamp'] = timeserie.index
情况2:时间戳字段名不是'stamp'
如果查看数据后发现时间戳的字段名是其他名称(如time、datetime),直接替换字段名即可:
timeserie['stamp'] = pd.to_datetime(timeserie['实际时间戳字段名'])
情况3:原始数据无时间戳
若确认speedmat里没有时间戳数据,需要检查原始pickle文件的生成逻辑,补充时间戳信息后再读取。
内容的提问来源于stack exchange,提问作者Lamine BENHABILES
相关产品推荐
相关产品推荐

