pandas 中 \`header = None\` 和 \`header = 0\` 的区别

新手上路,请多包涵

我正在编写代码以使用 --- 读取 csv 文件 pandas 我看到了一些奇怪的包功能。我的文件有我想忽略的列名,所以我使用 header = 0'infer' 而不是 None 。但我看到了一些奇怪的东西。

When I use None and I want to get a specific column, I just need to do df[column_index] but when I use 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 返回自我。 _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: 列索引

在处理上述异常的过程中,又出现了一个异常:

回溯(最近调用最后):文件“”,第 1 行,在文件“/home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/frame.py”,第 2139 行,在 getitem 返回 self._getitem_column(key) 文件“/home/sarvagya/anaconda3/envs/tf/lib/python3.6/site-packages/pandas/core/frame.py”,第 2146 行,在 _getitem_column 返回自我。 _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 return 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 文件“啪ndas/_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

有人可以帮忙吗?为什么会这样?

原文由 Sarvagya Gupta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 685
1 个回答

使用带标题的数据框时会出现差异,所以假设您的数据框 df 有标题!

  1. header=None pandas 自动将第一行 df (这是实际的列名)分配给第一行,因此你的列不再有名称

  2. header=0 ,熊猫首先删除列名(标题),然后为它们分配新的列名(仅当您在加载文件时传递 names = […….] )。 read_csv( filepath, header = 0 , names = ['....' , '....' ...])

希望能帮助到你!

原文由 Muffler 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进