![](/img/trans.png)
[英]KeyError: "None of [['', '']] are in the [columns]" (Pandas Dataframe)
[英]KeyError altering columns in dataframe
我正在尝试更改列或处理列,但出现了一些 keyError 错误。 致力于芝加哥犯罪数据分析。
例如,当我尝试跑步时
ds["DATE OF OCCURRENCE"] = pd.to_datetime([ds["DATE OF OCCURRENCE"]], format="%m/%d/%Y %I:%M:%S %p")
密钥错误
Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
完整代码:
import pandas as pd
url="https://data.cityofchicago.org/api/views/x2n5-8w5q/rows.csv?accessType=DOWNLOAD"
df= pd.read_csv(url)
ds = df.copy()
ds["DATE OF OCCURRENCE"] = pd.to_datetime([ds["DATE OF OCCURRENCE"]], format="%m/%d/%Y %I:%M:%S %p")
这是错误:
2896 尝试:-> 2897 返回 self._engine.get_loc(key) 2898 除了 KeyError:
pandas/_libs/index.pyx 在 pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx 在 pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '发生日期'
在处理上述异常的过程中,又发生了一个异常:
KeyError Traceback(最近一次调用最后一次)2 帧 /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2897 return self._engine .get_loc(key) 2898 除了 KeyError: -> 2899 返回 self._engine.get_loc(self._maybe_cast_indexer(key)) 2900
indexer = self.get_indexer([key], method=method, tolerance=tolerance) 2901 如果 indexer.ndim > 1 或 indexer.size > 1:pandas/_libs/index.pyx 在 pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx 在 pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '发生日期'
您的列已重命名,因此需要Crime_Date
并为Series
仅选择一个[]
列:
ds["Crime_Date"] = pd.to_datetime(ds["Crime_Date"], format="%m/%d/%Y %I:%M:%S %p")
编辑:
列名中有一些空格,因此需要:
ds["DATE OF OCCURRENCE"] = pd.to_datetime(ds["DATE OF OCCURRENCE"], format="%m/%d/%Y %I:%M:%S %p")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.