我遇到了一个我不理解的KeyError。
这是我的代码:
print(PERIODS)
print(PRODUCTS, '\n')
print(production, '\n')
print(demand, '\n')
SETUP_ITEMS = [[] for t in PERIODS]
for t in PERIODS:
print("\n t =", t)
for k in PRODUCTS:
print("k =", k)
if production[k][t]==(max(0,demand[k][t]-stock[k][t])) > 0:
SETUP_ITEMS[t].append(k)
print(SETUP_ITEMS)
这是输出:
range(1, 7)
range(1, 3)
1 2 3 4 5 6
1 110 49 0 82 40 65
2 48 75 15 10 15 70
1 2 3 4 5 6
1 110 49 0 82 40 65
2 48 75 15 10 15 70
t = 1
k = 1
k = 2
t = 2
k = 1
k = 2
t = 3
k = 1
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-35-8b6f312053ac> in <module>()
8 for k in PRODUCTS:
9 print("k =", k)
---> 10 if production[k][t]==(max(0,demand[k][t]-stock[k][t])) > 0:
11 SETUP_ITEMS[t].append(k)
12 print(SETUP_ITEMS)
/Users/frederic/anaconda/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
599 key = com._apply_if_callable(key, self)
600 try:
--> 601 result = self.index.get_value(self, key)
602
603 if not is_scalar(result):
/Users/frederic/anaconda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
2426 try:
2427 return self._engine.get_value(s, k,
-> 2428 tz=getattr(series.dtype, 'tz', None))
2429 except KeyError as e1:
2430 if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4363)()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4046)()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5085)()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:13913)()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:13857)()
KeyError: 3
我已将所有打印命令放在那里,因此您了解数据基础,以便我可以看到循环崩溃的位置。
此时需求等于生产,但生产将在代码中稍后进行操作,因此我需要这种分离。
PERIODS,PRODUCTS,demand等的数据来自Excel文件(通过openpyxl和pandas)。之前我有这部分代码,但没有与Excel的链接,没有其他变量作为DataFrames(范围是基于0的)。它工作得很好。有人可以解释一下这里的问题是什么吗?我想要几个小时,我的大脑慢慢开始融化。 ( - :
我想要的输出是t
列表,其中包含符合条件的所有k
个产品。
谢谢!