pandas.DataFrame.query keeping original multiindex
<p>I have a dataframe with multiindex:</p>

<pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.randint(0,5,(6, 2)), columns=['col1','col2'])
&gt;&gt;&gt; df['ind1'] = list('AAABCC')
&gt;&gt;&gt; df['ind2'] = range(6)
&gt;&gt;&gt; df.set_index(['ind1','ind2'], inplace=True)

&gt;&gt;&gt; df
           col1  col2
ind1 ind2            
A    0        2     0
     1        2     2
     2        1     2
B    3        2     2
C    4        4     0
     5        1     4
</code></pre>

<p>when I select data using <code>.loc[]</code> on one of the index levels, and apply <code>.query()</code> afterwards, resulting index is "shrinked" as expected to match only those values contained in resulting dataframe:</p>

<pre><code>&gt;&gt;&gt; df.loc['A'].query('col2 == 2')

      col1  col2
ind2            
1        2     2
2        1     2

&gt;&gt;&gt; df.loc['A'].query('col2 == 2').index

Int64Index([1, 2], dtype='int64', name='ind2')
</code></pre>

<p>however when I try to recieve same result using just <code>.query()</code>, pandas keeps the same index as on original dataframe (despite the fact, that it didn't behave like that above, in the case of single index - resulting index went from <code>[0,1,2]</code> to <code>[1,2]</code>, matching only <code>col2 == 2</code> rows):</p>

<pre><code>&gt;&gt;&gt; df.query('ind1 == "A" &amp; col2 == 2')

           col1  col2
ind1 ind2            
A    1        2     2
     2        1     2

&gt;&gt;&gt; df.query('ind1 == "A" &amp; col2 == 2').index

MultiIndex(levels=[['A', 'B', 'C'], [0, 1, 2, 3, 4, 5]],
           labels=[[0, 0], [1, 2]],
           names=['ind1', 'ind2'])
</code></pre>

<p>is it a bug or a feature? if feature, could you please explain such behavior?</p>

<p>EDIT1:
I would expect following index instead:</p>

<pre><code>MultiIndex(levels=[['A'], [1, 2]],
           labels=[[0, 0], [0, 1]],
           names=['ind1', 'ind2'])
</code></pre>

<p>EDIT2:
as explained in <a href="http://stackoverflow.com/questions/32585009/dataframe-slice-does-not-remove-index-values">Dataframe Slice does not remove Index Values</a> index values shouldn't be removed at all when slicing DF; such behavior should give following result: </p>

<pre><code>&gt;&gt;&gt; df.loc['A'].query('col2 == 2')

      col1  col2
ind2            
1        2     2
2        1     2

&gt;&gt;&gt; df.loc['A'].query('col2 == 2').index

EXPECTATION: Int64Index([0, 1, 2], dtype='int64', name='ind2')
REALITY:     Int64Index([1, 2], dtype='int64', name='ind2')
</code></pre>

<p><code>df.loc[A]</code> returns you a DF (or a "view") with a regular ("single") index:</p>

<pre><code>In [12]: df.loc['A']
Out[12]:
      col1  col2
ind2
0        1     1
1        0     3
2        1     2
</code></pre>

<p>so <code>.query()</code> will be applied on that DF with a regular index...</p>

python pandas dataframe multi-index