how to check in a pandas DataFrame entry exists by (index, column)
<p>I have searched and searched but I can't find how to test whether a pandas data frame entry exists by (index, column).</p>

<p>for example:</p>

<pre><code>import pandas
df = pandas.DataFrame()

df.ix['apple', 'banana'] = 0.1
df.ix['apple', 'orange'] = 0.1
df.ix['kiwi', 'banana'] = 0.2
df.ix['kiwi', 'orange'] = 0.7

df
       banana  orange
apple     0.1     0.1
kiwi      0.2     0.7
</code></pre>

<p>Now I want to test whether an entry exists</p>

<pre><code>if (["apple", "banana"] in df)
</code></pre>

<p>.. should be <strong>True</strong></p>

<p>and </p>

<pre><code>if (["apple", "apple"] in df)
</code></pre>

<p>.. should be <strong>False</strong></p>

<hr>

<p>Actually the reason I'm testing for existence is because the following doesn't work</p>

<pre><code>some loop ..
    df[wp] += some_value
    pass
</code></pre>

<p>It fails when df[wp] doesn't exist. This does work if the expression is</p>

<pre><code>some loop ..
    df[wp] += some_value
    pass
</code></pre>

<p>because pandas does have the idea of extending an array through assignment.</p>

<p>You can check for the existence in index and columns:</p>

<pre><code>('kiwi' in df.index) and ('apple' in df.columns)
</code></pre>

<p>Or you can use a try/except block:</p>

<pre><code>try:
    df.ix['kiwi', 'apple'] += some_value
except KeyError:
    df.ix['kiwi', 'apple'] = some_value
</code></pre>

<p>Note that DataFrames' shapes are not meant to be dynamic. This may slow down your operations heavily. So it might be better to do these things with dictionaries and finally turn them into DataFrames.</p>

python pandas