python-3.x - 熊猫中`header = None`和`header = 0`之间的区别
问题描述
我正在编写一个代码来读取一个csv
文件pandas
,我看到了这个包的一些奇怪的功能。我的文件有我想忽略的列名,所以我使用header = 0
or'infer'
代替None
. 但我看到了一些奇怪的东西。
当我使用None
并且想要获取特定列时,我只需要这样做,df[column_index]
但是当我使用0
or时'infer'
,我需要这样做df.ix[:,column_index]
才能获取列,否则df[column_index]
会出现以下错误:
回溯(最后一次调用):文件“/home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/indexes/base.py”,第 2525 行,在 get_loc 返回 self。 _engine.get_loc(key) 文件“pandas/_libs/index.pyx”,第 117 行,在 pandas._libs.index.IndexEngine.get_loc 文件“pandas/_libs/index.pyx”,第 139 行,在 pandas._libs.index .IndexEngine.get_loc 文件“pandas/_libs/hashtable_class_helper.pxi”,第 1265 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件“pandas/_libs/hashtable_class_helper.pxi”,第 1273 行,在 pandas._libs.hashtable.PyObjectHashTable .get_item KeyError: column_index
在处理上述异常的过程中,又出现了一个异常:
回溯(最后一次调用):文件“”,第 1 行,文件“/home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/frame.py”,第 2139 行, 在getitem return self._getitem_column(key) 文件“/home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/frame.py”,第 2146 行,在 _getitem_column return self._get_item_cache(key ) 文件“/home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/generic.py”,第 1842 行,在 _get_item_cache 值 = self._data.get(item) 文件中“ /home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/internals.py”,第 3843 行,在 get loc = self.items.get_loc(item) 文件“/home/ sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/indexes/base.py”,第 2527 行,在 get_loc 返回 self._engine.get_loc(self._maybe_cast_indexer(key)) 文件“ pandas/_libs/index.pyx”,第 117 行,在 pandas._libs.index.IndexEngine.get_loc 文件中“pandas/_libs/index.pyx”,第 139 行,pandas._libs.index.IndexEngine.get_loc 文件“pandas/_libs/hashtable_class_helper.pxi”,第 1265 行,pandas._libs.hashtable.PyObjectHashTable.get_item 文件“pandas/ _libs/hashtable_class_helper.pxi",第 1273 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: column_index
有人可以帮忙吗?为什么会这样?
解决方案
使用带有标头的数据框时会出现差异,因此可以说您的 DataFramedf
有标头!
header=None
pandas 自动将第一行df
(这是实际的列名)分配给第一行,因此您的列不再有名称header=0
,熊猫首先删除列名(标题),然后为它们分配新的列名(仅当您在加载文件时传递 names = [........] 时)。read_csv( filepath, header = 0 , names = ['....' , '....' ...])
希望能帮助到你!
推荐阅读
- javascript - 如何使用 Laravel + React 检查上传文件的类型?
- javascript - 如何使用 Jest 测试 Node.js 脚本的“if (require.main === module)”部分中的代码?
- python-imaging-library - 从原始字节确定 PNG 的大小
- java-7 - Weblogic 托管服务器自动断开连接
- odoo - 如何覆盖 website_slides CSS?
- ruby-on-rails - rails 中的模拟模型返回数组而不是模型对象
- python - 从导入的 JSON 返回特定值
- autodesk-forge - Autodesk Forge Viewer:更改 IFC 模型中的纹理
- python - Gunicorn + nginx 502 Bad Gateway 上的 Flask 应用程序
- python - 运行“python示例/train.py singleagent_ring”时出现语法错误