我已经使用熊猫成功读取了一个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()) 我认为可能有2个问题(显然):
1.列名中的空格(也可能在数据中)
解决方案是strip列名称中的空格:
strip
reviews_new.columns = reviews_new.columns.str.strip()
或将参数添加skipinitialspace到read_csv:
skipinitialspace
read_csv
reviews_new = pd.read_csv("D:\\aviva.csv", skipinitialspace=True)
2.默认使用不同的分隔符 ,
解决方案是添加参数sep:
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:
1.solutions
print (reviews_new.columns.tolist()) ['Name', ' Date', ' review'] ^ ^