Filtering syntax for pandas dataframe groupby with logic condition
<p>I have a pandas dataframe containing indices that have a one-to-many relationship.  A very simplified and shortened example of my data is shown in the <a href="https://i.stack.imgur.com/7z1ih.jpg" rel="nofollow">DataFrame Example</a> link.  I want to get a list or Series or ndarray of the unique namIdx values in which nCldLayers &lt;= 1.  The final result should show indices of 601 and 603.</p>

<ol>
<li><p>I am able to accomplish this with the 3 statements below, but I am wondering if there is a much better, more succinct way with perhaps 'filter', 'select',  or 'where'.</p>

<pre><code>grouped=(namToViirs['nCldLayers']&lt;=1).groupby(namToViirs.index).all(axis=0)
grouped = grouped[grouped==True]
filterIndex = grouped.index
</code></pre></li>
<li><p>Is there a better approach in accomplishing this result by applying the logical condition (namToViirs['nCldLayers >= 1) in a subsequent part of the chain, i.e., first group then apply logical condition, and then retrieve only the namIdx where the logical result is true for each member of the group?</p></li>
</ol>

<p>I think your code works nice, only you can add use small changes:</p>

<p>In <code>all</code> can be omit <code>axis=0</code><br>
<code>grouped==True</code> can be omit <code>==True</code>  </p>

<pre><code>grouped=(namToViirs['nCldLayers']&lt;=1).groupby(level='namldx').all()
grouped = grouped[grouped]
filterIndex = grouped.index
print (filterIndex)
Int64Index([601, 603], dtype='int64', name='namldx')
</code></pre>

<p>I think better is first filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and then <code>groupby</code>, because less loops -> better performance.</p>

python pandas dataframe