【发布时间】:2021-09-09 16:33:20
【问题描述】:
我是数据分析的新手,所以我试图理解代码。但我对这段代码有疑问:
def univariate_data(dataset, start_index, end_index, history_size, target_size):
data = []
labels = []
start_index = start_index + history_size
if end_index is None:
end_index = len(dataset) - target_size
for i in range(start_index, end_index):
indices = range(i-history_size, i)
# Reshape data from (history_size,) to (history_size, 1)
data.append(np.reshape(dataset[indices], (history_size, 1)))
labels.append(dataset[i+target_size])
return np.array(data), np.array(labels)
History_size 是最后一个时间间隔的大小,target_size 是一个参数,用于确定模型应该学习预测的未来多远。也就是说,target_size 就是要预测的目标向量。 当我这样调用这个函数时:
univariate_past_history = 20
univariate_future_target = 0
TRAIN_SPLIT = 2000
x_train_uni, y_train_uni = univariate_data(uni_data, 0, TRAIN_SPLIT,
univariate_past_history,
univariate_future_target)
我有错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-25-148d84980a5b> in <module>()
5 x_train_uni, y_train_uni = univariate_data(uni_data, 0, TRAIN_SPLIT,
6 univariate_past_history,
----> 7 univariate_future_target)
<ipython-input-23-74f4c24fbf96> in univariate_data(dataset, start_index, end_index, history_size, target_size)
9 indices = range(i-history_size, i)
10 # Reshape data from (history_size,) to (history_size, 1)
---> 11 data.append(np.reshape(dataset[indices], (history_size, 1)))
12 labels.append(dataset[i+target_size])
13 return np.array(data), np.array(labels)
C:\Users\danil\.conda\envs\p35\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
1069 key = com.apply_if_callable(key, self)
1070 try:
-> 1071 result = self.index.get_value(self, key)
1072
1073 if not is_scalar(result):
C:\Users\danil\.conda\envs\p35\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
4728 k = self._convert_scalar_indexer(k, kind="getitem")
4729 try:
-> 4730 return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
4731 except KeyError as e1:
4732 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
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: range(0, 20)
有人可以帮忙处理这部分代码吗? 我该如何解决这个错误?
【问题讨论】:
-
虽然问题行有
reshape函数,但是回溯显示错误在pandas系列索引中,发生在调用reshape之前。
标签: python python-3.x pandas dataframe numpy