tefutb 2021-07-21 15:55 采纳率: 100%
浏览 2321
已采纳

在使用loc条件判断时出现KeyError: 'data'


import pandas as pd
c=str(input())
d=int(input())
path='counties.csv'
df=pd.read_csv(path)
df.loc[:,'date']=df['date'].str.replace('/','').astype('int32')
print(df.head())
print(df.loc[(df['county']==c)&(df['data']=='2020124'),:])

为什么会出现
date county state cases deaths
0 2020121 Snohomish Washington 1 0
1 2020122 Snohomish Washington 1 0
2 2020123 Snohomish Washington 1 0
3 2020124 Cook Illinois 1 0
4 2020124 Snohomish Washington 1 0
Traceback (most recent call last):
File "D:\pycharm python\venv\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'data'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "D:\pycharm python\小学期\ibc.py", line 8, in
print(df.loc[(df['county']==c)&(df['data']=='2020124'),:])
File "D:\pycharm python\venv\lib\site-packages\pandas\core\frame.py", line 3024, in getitem
indexer = self.columns.get_loc(key)
File "D:\pycharm python\venv\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 'data'

  • 写回答

1条回答 默认 最新

  • CSDN专家-HGJ 2021-07-21 15:59
    关注

    是把date写成了data,应该是df['date']=='2020124',这样改一下即可

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 7月22日
  • 创建了问题 7月21日

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失