错误:pandas 哈希表 keyerror [英] Error: pandas hashtable keyerror

查看:24
本文介绍了错误:pandas 哈希表 keyerror的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地使用 Pandas 读取了一个 csv 文件.当我尝试从数据框中打印特定列时,我收到了 keyerror.在此,我与错误共享代码.

I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.

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:Users30216AppDataLocalContinuumAnaconda2libsite-packagespandascoreframe.py", line 1997, in __getitem__
    return self._getitem_column(key)
  File "C:Users30216AppDataLocalContinuumAnaconda2libsite-packagespandascoreframe.py", line 2004, in _getitem_column
    return self._get_item_cache(key)
  File "C:Users30216AppDataLocalContinuumAnaconda2libsite-packagespandascoregeneric.py", line 1350, in _get_item_cache
    values = self._data.get(item)
  File "C:Users30216AppDataLocalContinuumAnaconda2libsite-packagespandascoreinternals.py", line 3290, in get
    loc = self.items.get_loc(item)
  File "C:Users30216AppDataLocalContinuumAnaconda2libsite-packagespandasindexesase.py", line 1947, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandasindex.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandasindex.c:4154)
  File "pandasindex.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandasindex.c:4018)
  File "pandashashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandashashtable.c:12368)
  File "pandashashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandashashtable.c:12322)
KeyError: 'review'

**

有人可以帮我吗?

推荐答案

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

I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:

print (reviews_new.columns.tolist())

<小时>

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


I think there can be 2 problems (obviously):

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

解决方案是strip 列名中的空格:

Solutions are strip whitespaces in column names:

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

或将参数 skipinitialspace 添加到 read_csv:

Or add parameter skipinitialspace to read_csv:

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)

列名中有空格,所以需要1.solutions:

You get whitespace in column name, so need 1.solutions:

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

这篇关于错误:pandas 哈希表 keyerror的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆