How to use a dict to subset a DataFrame?
<p>Say, I have given a DataFrame with most of the columns being categorical data.</p>

<pre><code>&gt; data.head()
  age risk     sex smoking
0  28   no    male      no
1  58   no  female      no
2  27   no    male     yes
3  26   no    male      no
4  29  yes  female     yes
</code></pre>

<p>And I would like to subset this data by a dict of key-value pairs for those categorical variables.</p>

<pre><code>tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'}
</code></pre>

<p>Hence, I would like to have the following subset.</p>

<pre><code>data[ (data.risk == 'no') &amp; (data.smoking == 'yes') &amp; (data.sex == 'female')]
</code></pre>

<p>What I want to do is:</p>

<pre><code>data[tmp]
</code></pre>

<p>What is the most python / pandas way of doing this?</p>

<hr>

<p>Minimal example:</p>

<pre><code>import numpy as np
import pandas as pd
from pandas import Series, DataFrame

x = Series(random.randint(0,2,50), dtype='category')
x.cat.categories = ['no', 'yes']

y = Series(random.randint(0,2,50), dtype='category')
y.cat.categories = ['no', 'yes']

z = Series(random.randint(0,2,50), dtype='category')
z.cat.categories = ['male', 'female']

a = Series(random.randint(20,60,50), dtype='category')

data = DataFrame({'risk':x, 'smoking':y, 'sex':z, 'age':a})

tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'}
</code></pre>

<p>I think you can could use the <code>to_dict</code> method on your dataframe, and then filter using a list comprehension:</p>

<pre class="lang-python prettyprint-override"><code>df = pd.DataFrame(data={'age':[28, 29], 'sex':["M", "F"], 'smoking':['y', 'n']})
print df
tmp = {'age': 28, 'smoking': 'y', 'sex': 'M'}

print pd.DataFrame([i for i in df.to_dict('records') if i == tmp])


&gt;&gt;&gt;    age sex smoking
0   28   M       y
1   29   F       n

   age sex smoking
0   28   M       y
</code></pre>

<p>You could also convert tmp to a series:</p>

<pre><code>ts = pd.Series(tmp)

print pd.DataFrame([i[1] for i in df.iterrows() if i[1].equals(ts)])
</code></pre>

python pandas dataframe categorical-data