【发布时间】:2020-10-17 21:12:51
【问题描述】:
我有以下 csv 结构文件。
时间
01/01/2010 00:00
01/01/2010 00:10
... 消费和消费2文件都是相同的(唯一的区别是行号)。第一列对应于时间格式 01/01/2010 00:00:00。以下 199 列对应于需求值。我认为问题出在第一列格式。
代码如下:
import matplotlib.pyplot as plt
import numpy as
from sklearn.cluster import KMeans
import datetime as dt
import matplotlib.patches as mpatches
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
data=pd.read_csv('Consumption.csv',header=None, sep='\n')#, sep='\t')
data.head()
data['Timestamp']=pd.to_datetime(data['Time'])
plt.figure(num=1, figsize=(10,5))
data.Timestamp.plot() #Plotting the newly added timestamp column
plt.xlabel('Reading Count')
plt.ylabel('Date')
plt.show()
我尝试将时间转换为时间戳,但由于出现以下错误,我无法绘制数据: 我似乎是时间戳的问题。您对如何解决这个问题有什么建议吗?
1 #Converting time to timestamp ( a datetime object)
----> 2 data['Timestamp']=pd.to_datetime(data['Time'])
3
4 # Ensuring there are no temporal gaps
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/opt/anaconda3/envs/python3b/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: 'Time'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-9-9b4c885821b2> in <module>
1 #Converting time to timestamp ( a datetime object)
----> 2 data['Timestamp']=pd.to_datetime(data['Time'])
3
4 # Ensuring there are no temporal gaps
5 plt.figure(num=1, figsize=(10,5))
~/opt/anaconda3/envs/python3b/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
~/opt/anaconda3/envs/python3b/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2650 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: 'Time'
【问题讨论】:
-
您确定您传递的列名正确吗?
-
是的,我确定。第一列名为“时间”,它包含的值格式为 01/01/2010 00:00。第二列名为 H1,第三列 H2 等。我真的不知道如何解决这个问题。完整的 cvs 文件在这里:github.com/charlicruz/Energy-Demand。非常感谢
标签: python pandas dataframe csv matplotlib