gpt4 book ai didi

python - KeyError 更改数据框中的列

转载 作者:行者123 更新时间:2023-12-05 05:07:29 28 4
gpt4 key购买 nike

我正在尝试更改列或处理列,但出现一些 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 try:-> 2897 return self._engine.get_loc(key) 2898 except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi inpandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi inpandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'DATE OF OCCURRENCE'

During handling of the above exception, another exception occurred:

KeyError Traceback (most recent calllast) 2 frames/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py inget_loc(self, key, method, tolerance) 2897 returnself._engine.get_loc(key) 2898 except KeyError:-> 2899 return self._engine.get_loc(self._maybe_cast_indexer(key)) 2900
indexer = self.get_indexer([key], method=method, tolerance=tolerance)2901 if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi inpandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi inpandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'DATE OF OCCURRENCE'

最佳答案

您的列已重命名,因此需要 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")

关于python - KeyError 更改数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114670/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com