【问题标题】:Adding two columns in pandas.dataframe using assign, and get error message said KeyError使用 assign 在 pandas.dataframe 中添加两列,并得到错误消息说 KeyError
【发布时间】:2020-10-16 18:55:40
【问题描述】:

我试图在我的数据报中添加更多列,但我收到一条错误消息,说 KeyError: 'H00——01——TC',这是我的 CSV 中的列标题,有什么办法可以解决它?谢谢各位

 LD = pd.read_csv(Y21_DM, header=0,low_memory=False)

 CR = pd.read_csv(Crash_Rate, header=0,low_memory=False)

TOTAL = LD.merge(CR, left_on = ['LINKTYPE','SPEEDLIMIT'], right_on = ['LINKTYPE','SPEEDLIMIT'])

aaa = TOTAL.assign(H00_01_TC_ALL=(TOTAL['H00_01_TC']+TOTAL['H18_07_IXD'])/60)

print(aaa)

这是我收到的错误消息:

Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'H00_01_TC'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/User/Desktop/Learning/Python/BCR.py", line 121, in <module>
    aaa = TOTAL.assign(H00_01_TC_ALL=(TOTAL['H00_01_TC']+TOTAL['H18_07_IXD'])/60)
  File "C:\Program Files\Python37\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Program Files\Python37\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'H00_01_TC'

【问题讨论】:

  • 哎呀,消息基本上是说'H00_01_TC'列似乎由于某种原因丢失了。你确定它存在于'TOTAL'中吗?
  • 谢谢你,我认为你是对的......我拼错了列名......

标签: python pandas numpy dataframe csv


【解决方案1】:

您能否运行此代码查看列列表,然后检查列“H00_01_TC”是否存在或拼写是否有问题。

TOTAL.columns

【讨论】:

  • 谢谢伊恩,看来我错过了我的专栏名称的拼写...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 2012-05-10
  • 1970-01-01
  • 2015-01-01
  • 2013-03-30
  • 1970-01-01
相关资源
最近更新 更多