【问题标题】:KeyError: "None of [Index(['23/01/2020' ......,\n dtype='object', length=9050)] are in the [columns]"KeyError:“[Index(['23/01/2020' ......,\n dtype='object', length=9050)] 均不在 [columns] 中”
【发布时间】:2021-01-06 09:40:26
【问题描述】:

我正在通过使用一些公共数据集自学 pandas 和 matplotlib this api link

我正在使用 colab,以下是我的代码:

import datetime 
import io
import json
import pandas as pd
import requests
import matplotlib.pyplot as plt

confirm_resp = requests.get('https://api.data.gov.hk/v2/filterq=%7B%22resource%22%3A%22http%3A%2F%2Fwww.chp.gov.hk%2Ffiles%2Fmisc%2Fenhanced_sur_covid_19_eng.csv%22%2 C%22section%22%3A1%2C%22format%22%3A%22json%22%7D').content

confirm_df = pd.read_json(io.StringIO(confirm_resp.decode('utf-8')))
confirm_df.columns = confirm_df.columns.str.replace(" ", "_")
pd.to_datetime(confirm_df['Report_date'])
confirm_df.columns = ['Case_no', 'Report_date', 'Onset_date', 'Gender', 'Age', 
'Name_of_hospital_admitted', 'Status', 'Resident', 'Case_classification', 'Confirmed_probable']
confirm_df = confirm_df.drop('Name_of_hospital_admitted', axis = 1)
confirm_df.head()

这就是数据框的样子:

Case_no Report_date Onset_date Gender Age Status Resident Case_classification Confirmed_probable
1 23/01/2020 21/01/2020 M 39 Discharged Non-HK resident Imported case Confirmed
2 23/01/2020 18/01/2020 M 56 Discharged HK resident Imported case Confirmed
3 24/01/2020 20/01/2020 F 62 Discharged Non-HK resident Imported case Confirmed
4 24/01/2020 23/01/2020 F 62 Discharged Non-HK resident Imported case Confirmed
5 24/01/2020 23/01/2020 M 63 Discharged Non-HK resident Imported case Confirmed

当我尝试用下面的代码做一个简单的情节时:

x = confirm_df['Report_date']
y = confirm_df['Case_classification']
confirm_df.plot(x, y)

它给了我以下错误:

KeyError                                  Traceback (most recent call last)
<ipython-input-17-e4139a9b5ef1> in <module>()
      4 y = confirm_df['Case_classification']
      5 
----> 6 confirm_df.plot(x, y)
3 frames
/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py in __call__(self, *args, **kwargs)
    912                 if is_integer(x) and not data.columns.holds_integer():
    913                     x = data_cols[x]
--> 914                 elif not isinstance(data[x], ABCSeries):
    915                     raise ValueError("x must be a label or position")
    916                 data = data.set_index(x)
/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in __getitem__(self, key)
   2910             if is_iterator(key):
   2911                 key = list(key)
-> 2912             indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
   2913 
   2914         # take() does not accept boolean indexers
/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _get_listlike_indexer(self, key, axis, raise_missing)
   1252             keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr)
   1253 
-> 1254         self._validate_read_indexer(keyarr, indexer, axis, raise_missing=raise_missing)
   1255         return keyarr, indexer
   1256 
/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)
   1296             if missing == len(indexer):
   1297                 axis_name = self.obj._get_axis_name(axis)
-> 1298                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1299 
   1300             # We (temporarily) allow for some missing keys with .loc, except in
KeyError: "*None of [Index(['23/01/2020', '23/01/2020', '24/01/2020', '24/01/2020', '24/01/2020',\n       '26/01/2020', '26/01/2020', '26/01/2020', '29/01/2020', '29/01/2020',\n       ...\n       '05/01/2021', '05/01/2021', '05/01/2021', '05/01/2021', '05/01/2021',\n       '05/01/2021', '05/01/2021', '05/01/2021', '05/01/2021', '05/01/2021'],\n      dtype='object', length=9050)] are in the [column*s]"

我尝试在将Report date 转换为日期时间对象和不转换为日期时间对象的情况下制作绘图,我尝试用数据框中的所有列替换x 值,但都给了我相同的错误代码。

如果有人可以帮助我了解如何在此处处理这些问题并继续前进,不胜感激。我花了几个小时来解决它,但找不到答案。

在我从 Kaggle 下载一些笔记本和数据集以进行跟进之前,我没有遇到过这个问题。

谢谢你,新年快乐。

【问题讨论】:

  • 尝试通过 x.values 在 np.ndarray 中转换它怎么样?

标签: python-3.x pandas dataframe matplotlib


【解决方案1】:

首先,您需要将转换后的日期分配回列:

confirm_df['Report_date'] = pd.to_datetime(confirm_df['Report_date'])

其次,当从数据框对象调用plot 方法时,您只需提供列名作为参数(1)。

confirm_df.plot(x='Report_date', y='Case_classification')

但上面的代码仍然会抛出错误,因为'Case_classification'不是数字数据。

您正在尝试绘制日期时间与分类数据,因此正常的绘图将不起作用,但这样的事情可能会起作用 (2):

# I used only first 15 examples here, full dataset is kinda messy
confirm_df.iloc[:15, :].groupby(['Report_date', 'Case_classification']).size().unstack().plot.bar()

(1)pandas.DataFrame.plot

(2)How to plot categorical variable against a date column in Python

【讨论】:

  • 它有效,非常感谢。所以问题是我必须使用 groupby 来聚合我想要绘制的项目。
【解决方案2】:

几个问题。首先,链接不正确,我已经编辑了它们(可能只是复制/粘贴错误)。其次,您必须将转换后的日期时间序列分配回数据框。使用print(confirm_df.dtypes) 查看差异。 然后,数据集不是按日期排序的,但 matplotlib 需要一个有序的 x 轴。 实际上,问题在于解析器误解了日期时间对象。我添加了dayfirst=True 以确保正确读取日期。最后,你想在这里绘制什么?只是按日期的案件?按日期每组的病例数?您的原始代码仅暗示前者,但这并不能提供真正的信息,是吗?

import io
import pandas as pd
import requests
import matplotlib.pyplot as plt

print("starting download")
confirm_resp = requests.get('https://api.data.gov.hk/v2/filter?q=%7B%22resource%22%3A%22http%3A%2F%2Fwww.chp.gov.hk%2Ffiles%2Fmisc%2Fenhanced_sur_covid_19_eng.csv%22%2C%22section%22%3A1%2C%22format%22%3A%22json%22%7D').content
print("finished download")

confirm_df = pd.read_json(io.StringIO(confirm_resp.decode('utf-8')))

confirm_df.columns = confirm_df.columns.str.replace(" ", "_")
confirm_df['Report_date'] = pd.to_datetime(confirm_df['Report_date'], dayfirst=True)
confirm_df.columns = ['Case_no', 'Report_date', 'Onset_date', 'Gender', 'Age', 
'Name_of_hospital_admitted', 'Status', 'Resident', 'Case_classification', 'Confirmed_probable']
confirm_df = confirm_df.drop('Name_of_hospital_admitted', axis = 1)

print(confirm_df.dtypes)

fig, ax = plt.subplots(figsize=(20, 5))
ax.plot(confirm_df['Report_date'], confirm_df['Case_classification'])
plt.tight_layout()
plt.show()

示例输出:

一些分组和数据聚合可能会提供更多信息,但您必须在编写代码之前先决定要显示的内容。

【讨论】:

  • 我正在输入和发布几乎完全相同的答案,第一个和第二个 ponits 等等。这么巧,要不要删帖? :) 我是新手,所以请指导。
  • 如果您添加 groupby 方法的输出,那么答案会有所不同。
  • 它有效,非常感谢。对我来说,另一个新事物是 dayfirst 参数。
猜你喜欢
  • 2021-01-08
  • 1970-01-01
  • 2021-08-04
  • 2019-09-16
  • 2022-11-18
  • 2020-05-10
  • 2020-05-20
  • 2021-10-15
  • 1970-01-01
相关资源
最近更新 更多