【问题标题】:Problem with reshaping dataset in NumPy in Python 3.9在 Python 3.9 中在 NumPy 中重塑数据集的问题
【发布时间】: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


【解决方案1】:

tl;dr:进行此更改:

for i in range(start_index, end_index):
    indices = pd.RangeIndex(i-history_size, i)

错误出现在表达式dataset[indices] 中。 indices 是一个 range 对象;该错误告诉您range(0, 20) 不是dataset[key] 的有效密钥。

根据回溯,看起来dataset 是一个pandas.Series 对象。 Series 对象可以接受索引序列作为键,并返回由指定索引处的条目组成的系列。

在 Python 中,range 对象不是序列,而只是包含定义范围的开始、停止和步长值的可迭代对象。因此,严格来说,它们本身并不是Series 的有效密钥。相反,您将需要 Pandas RangeIndex。它们与 Python range 对象一样,仅包含开始、停止和步长值,而不是范围内的每个值,因此与将 range 扩展为 list 或 Pandas Int64Index 相比,它们可以节省内存。但是,Pandas 知道如何使用它们来索引 Series

我不确定您运行的是什么版本的 Pandas,但在当前版本中,Pandas 将接受 Python range 对象作为 Series 的键,可能通过在内部将它们转换为 RangeIndex 对象。我还没有研究过但是,在旧版本中,尝试使用 range 对象作为 Pandas Series 的键会导致您遇到错误。

您可以将indices 转换为Pandas Index(Pandas 会自动将其转换为RangeIndex):

for i in range(start_index, end_index):
    indices = pd.Index(range(i-history_size, i))

或者,更简单地说,您可以直接创建一个RangeIndex

for i in range(start_index, end_index):
    indices = pd.RangeIndex(i-history_size, i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2017-01-13
    • 2011-10-01
    • 2019-05-05
    • 1970-01-01
    • 2013-01-06
    • 2020-11-26
    相关资源
    最近更新 更多