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

在使用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 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数