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>You can create a look up data frame from the dictionary and then do an inner join with the <code>data</code> which will have the same effect as <code>query</code>:</p>

<pre><code>from pandas import merge, DataFrame
merge(DataFrame(tmp, index =[0]), data)
</code></pre>

<p><a href="https://i.stack.imgur.com/xW4kf.png" rel="nofollow"><img src="https://i.stack.imgur.com/xW4kf.png" alt="enter image description here"></a></p>

python pandas dataframe categorical-data