pandas报错:KeyError:

使用pandas读取.csv文件,使用df['列名']的时候,总是报如下错误。
.csv文件如下:


image.png

报错如下:

Traceback (most recent call last):
File "C:\Users\zhangheng\anaconda3\envs\py36\lib\site-packages\pandas\core\indexes\base.py", line 2393, in get_loc
return self._engine.get_loc(key)
File "pandas_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas_libs\index.c:5239)
File "pandas_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas_libs\index.c:5085)
File "pandas_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas_libs\hashtable.c:20405)
File "pandas_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas_libs\hashtable.c:20359)
KeyError: '交易日期'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:/Quant/Practice/Code/xbx_stock_2019/program/pandas基础/5_缺失处理.py", line 25, in <module>
index = df[df['交易日期'].isin(['2019-03-01'])].index
File "C:\Users\zhangheng\anaconda3\envs\py36\lib\site-packages\pandas\core\frame.py", line 2062, in getitem
return self._getitem_column(key)
File "C:\Users\zhangheng\anaconda3\envs\py36\lib\site-packages\pandas\core\frame.py", line 2069, in _getitem_column
return self._get_item_cache(key)
File "C:\Users\zhangheng\anaconda3\envs\py36\lib\site-packages\pandas\core\generic.py", line 1534, in _get_item_cache
values = self._data.get(item)
File "C:\Users\zhangheng\anaconda3\envs\py36\lib\site-packages\pandas\core\internals.py", line 3590, in get
loc = self.items.get_loc(item)
File "C:\Users\zhangheng\anaconda3\envs\py36\lib\site-packages\pandas\core\indexes\base.py", line 2395, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas_libs\index.c:5239)
File "pandas_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas_libs\index.c:5085)
File "pandas_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas_libs\hashtable.c:20405)
File "pandas_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas_libs\hashtable.c:20359)
KeyError: '交易日期'

Process finished with exit code 1

原因:

import pandas as pd # 将pandas作为第三方库导入,我们一般为pandas取一个别名叫做pd

pd.set_option('expand_frame_repr', False) # 当列太多时清楚展示

=====导入数据

df = pd.read_csv(
r'D:\Quant\Practice\Code\xbx_stock_2019\data\a_stock_201903.csv',
encoding='gbk',
skiprows=1
)
在导入数据时,skiprows=1,即即读取.csv文件时,跳过了第一行的列名,没有读取列名,你使用 df['列名'] 就会报错

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容