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 would use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">.query()</a> method for this task:</p>

<pre><code>In [103]: qry = ' and '.join(["{} == '{}'".format(k,v) for k,v in tmp.items()])

In [104]: qry
Out[104]: "sex == 'female' and risk == 'no' and smoking == 'yes'"

In [105]: data.query(qry)
Out[105]:
   age risk     sex smoking
7   24   no  female     yes
22  43   no  female     yes
23  42   no  female     yes
25  24   no  female     yes
32  29   no  female     yes
40  34   no  female     yes
43  35   no  female     yes
</code></pre>

python pandas dataframe categorical-data