Pandas groupby object filtering
<p>i have a pandas dataframe</p>

<pre><code>df.columns
Index([uâcar_idâ,uâcolorâ,uâmakeâ,uâyearâ)]
</code></pre>

<p>I would like to create a new FILTERABLE object that has the count of each group (color,make,year);</p>

<pre><code>grp = df[[âcolorâ,âmakeâ,âyearâ]].groupby([âcolorâ,âmakeâ,âyearâ]).size()
</code></pre>

<p>which will return something like this</p>

<pre><code>color   make   year     count
black   honda  2011   416
</code></pre>

<p>I would like to be able to filter it, however when I try this:</p>

<pre><code>grp.filter(lambda x: x[âcolorâ]==âblackâ)
</code></pre>

<p>I receive this error</p>

<blockquote>
  <p>TypeError: 'function' object is not iterable</p>
</blockquote>

<p>How do I leverage a 'groupby' object in order to filter the rows out?</p>

<p><strong><em>Option 1</em></strong><br>
Filter ahead of time</p>

<pre><code>cols = ['color','make','year']
df[df.color == 'black', cols].grouby(cols).size()
</code></pre>

<p><strong><em>Option 2</em></strong>
Use <code>xs</code> for index cross sections</p>

<pre><code>cols = ['color','make','year']
grp = df[cols].groupby(cols).size()

df.xs('black', level='color', drop_level=False)
</code></pre>

<p>or</p>

<pre><code>df.xs('honda', level='make', drop_level=False)
</code></pre>

<p>or</p>

<pre><code>df.xs(2011, level='year', drop_level=False)
</code></pre>

python pandas indexing group-by condition