错误:pandas 哈希表 keyerror

2024-04-08

我已经使用 pandas 成功读取了 csv 文件。当我尝试从数据框中打印特定列时,我收到关键错误。特此,我分享带有错误的代码。

import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']

**

reviews_new['review']
Traceback (most recent call last):
  File "<ipython-input-43-ed485b439a1c>", line 1, in <module>
    reviews_new['review']
  File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__
    return self._getitem_column(key)
  File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache
    values = self._data.get(item)
  File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\internals.py", line 3290, in get
    loc = self.items.get_loc(item)
  File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
  File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
  File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
  File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: 'review'

**

有人可以帮我吗?


我认为首先最好调查一下,什么是真正的列名,如果转换为列表更好,会看到一些空格或类似的:

print (reviews_new.columns.tolist())

我认为可能有两个问题(显然):

1.列名中的空格(也可能在数据中)

解决方案是strip http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html列名中的空格:

reviews_new.columns = reviews_new.columns.str.strip()

或者添加参数skipinitialspace to read_csv http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html:

reviews_new = pd.read_csv("D:\\aviva.csv", skipinitialspace=True)

2.默认分隔符不同,

解决办法是添加参数sep:

#sep is ;
reviews_new = pd.read_csv("D:\\aviva.csv", sep=';')
#sep is whitespace
reviews_new = pd.read_csv("D:\\aviva.csv", sep='\s+')
reviews_new = pd.read_csv("D:\\aviva.csv", delim_whitespace=True)

EDIT:

您在列名称中出现空格,因此需要1.solutions:

print (reviews_new.columns.tolist())
['Name', ' Date', ' review'] 
          ^        ^

EDIT1:

如果没有列名 if 测试print (df.columns.tolist())并且无法选择 DataFrame 解决方案的第一个“列”df.index:

df = pd.DataFrame({'col':list('abc'),
                   'col1':list('efg'),
                   'col2':range(3)}).set_index('col1')

print (df)
     col  col2
col1          
e      a     0
f      b     1
g      c     2


print (df.columns.tolist())
['col', 'col2']

print (df.index)
Index(['e', 'f', 'g'], dtype='object', name='col1')

print (df.index.get_level_values('col1'))
Index(['e', 'f', 'g'], dtype='object', name='col1')

如果存在多重索引:

df = pd.DataFrame({'col':list('abc'),
                   'col1':list('efg'),
                   'col2':range(3)}).set_index(['col1', 'col'])

print (df)
          col2
col1 col      
e    a       0
f    b       1
g    c       2

print (df.index)
MultiIndex([('e', 'a'),
            ('f', 'b'),
            ('g', 'c')],
           names=['col1', 'col'])

print (df.index.get_level_values('col1'))
Index(['e', 'f', 'g'], dtype='object', name='col1')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

错误:pandas 哈希表 keyerror 的相关文章

随机推荐