Pandas: KeyError when attempting to print value from df.loc in Excel file
<p>I'm attempting to parse an Excel-file using Pandas.</p>

<pre><code>import pandas as pd
import xlrd

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

df = xl_file.parse("Sheet1")
</code></pre>

<p>Now, if I get a value (<code>name</code>) from the sheet:</p>

<pre><code>if len(df.loc[df["Col A"].str.contains("John"), "Col B"]) &gt; 0:
    name = df.loc[df["Col A"].str.contains("John"), "Col B"]
</code></pre>

<p>And then <code>print name</code>, the result is:</p>

<blockquote>
<pre><code>1    John Doe
Name: Col B, dtype: object
</code></pre>
</blockquote>

<p>or <code>print name.values</code>:</p>

<blockquote>
<pre><code>[u'John Doe']
</code></pre>
</blockquote>

<p>But if I try to retrieve the actual string with <code>print name[0]</code>, I get <code>KeyError</code>:</p>

<blockquote>
<pre><code>  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
</code></pre>
</blockquote>

<p>What could be the problem?</p>

<p><code>name</code> is a series, and <code>0</code> is not in the series' index (check <code>name.index</code>). This explains the error message.</p>

<p>If you want to select the first element in the series, do:</p>

<pre><code>name.iloc[0]
</code></pre>

python excel python-2.7 pandas