【发布时间】:2021-08-24 17:58:53
【问题描述】:
在 Kmeans 上拟合数据然后生成标签后,我正在为 Kmeans 使用 sklearn 库。我已将标签作为集群标签附加到数据集中。我想在每个集群中打印日期和状态名称。我做了4个集群。在集群 0 中打印状态之后,我得到一个 KeyError = 416 的错误。我不明白为什么会发生这个错误。请帮我解决。
for i in range(0,2):
print("\nCountries in Cluster " + str(i))
for j in range(0,len(data)):
if data['Cluster label'][j] == i:
print(data['date'][j],data['state'][j])
这是在数据集上运行上述代码的输出。打印集群 0 下的状态和日期后,会生成错误。我没有得到导致此错误发生的原因。
Countries in Cluster 0
2020-01-21 Washington
2020-01-22 Washington
2020-01-23 Washington
2020-01-24 Illinois
2020-01-24 Washington
2020-01-25 California
2020-01-25 Illinois
2020-01-25 Washington
2020-01-26 Arizona
2020-01-26 California
2020-01-26 California
2020-01-26 Illinois
2020-01-26 Washington
...
Error
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2894 try:
-> 2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
KeyError: 416
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-97-ef85b13c4238> in <module>
2 print("\nCountries in Cluster " + str(i))
3 for j in range(0,len(data)):
----> 4 if data['Cluster label'][j] == i:
5 print(data['date'][j],data['state'][j])
6
~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
880
881 elif key_is_scalar:
--> 882 return self._get_value(key)
883
884 if is_hashable(key):
~\anaconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
987
988 # Similar to Index.get_value, but we do not fall back to positional
--> 989 loc = self.index.get_loc(label)
990 return self.index._get_values_for_loc(self, loc, label)
991
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: 416
【问题讨论】: