首页 > 解决方案 > 熊猫中`header = None`和`header = 0`之间的区别

问题描述

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

当我使用None并且想要获取特定列时,我只需要这样做,df[column_index]但是当我使用0or时'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

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

标签: python-3.xpandascsvdataframe

解决方案


使用带有标头的数据框时会出现差异,因此可以说您的 DataFramedf有标头!

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

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

希望能帮助到你!


推荐阅读