2016-09-15 42 views
2

我試圖使用Pandas解析Excel文件。現在Pandas:嘗試從Excel文件中的df.loc打印值時出現KeyError

import pandas as pd 
import xlrd 

xl_file = pd.ExcelFile("file.xlsx") 

df = xl_file.parse("Sheet1") 

,如果我從片材的值(name):

if len(df.loc[df["Col A"].str.contains("John"), "Col B"]) > 0: 
    name = df.loc[df["Col A"].str.contains("John"), "Col B"] 

然後print name,其結果是:

1 John Doe 
Name: Col B, dtype: object 

print name.values

[u'John Doe'] 

但是,如果我嘗試檢索與print name[0]實際的字符串,我得到KeyError

File "pandas/core/series.py", line 583, in __getitem__ 
    result = self.index.get_value(self, key) 
    File "pandas/indexes/base.py", line 1980, in get_value 
    tz=getattr(series.dtype, 'tz', None)) 
    File "pandas/index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas/index.c:3332) 
    File "pandas/index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas/index.c:3035) 
    File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018) 
    File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6610) 
    File "pandas/hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6554) 
KeyError: 0 

可能是什麼問題呢?

回答

3

name是一個系列,並且0不在系列的索引(檢查name.index)。這解釋了錯誤信息。

如果你想在系列中選擇的第一要素,這樣做:

name.iloc[0] 
+0

謝謝,我猜我的Excel文件正在使用它自己的指標? (從在線來源下載)。我所查找的值的索引是'[1]'而不是'[0]'。 – Winterflags

+1

恐怕我不知道Excel行號和熊貓指數之間的關係。但是因爲'name'是過濾的結果(名字約翰),所以你無法事先知道哪些索引值將會或不會在索引中。 – IanS

相關問題