Pandas using row labels in boolean indexing

So, I have a DataFrame like this:

df = pd.DataFrame(np.random.randn(6, 3), columns=['a', 'b', 'c'])

      a         b         c
0  1.877317  0.109646  1.634978
1 -0.048044 -0.837403 -2.198505
2 -0.708137  2.342530  1.053073
3 -0.547951 -1.790304 -2.159123
4  0.214583 -0.856150 -0.477844
5  0.159601 -1.705155  0.963673

We can logically index it like this:

df[df.a > 0]

     a         b         c
0  1.877317  0.109646  1.634978
4  0.214583 -0.856150 -0.477844
5  0.159601 -1.705155  0.963673

We can also slice it using line shortcuts as follows:

df.ix[[0,2,4]]

    a         b         c
0  1.877317  0.109646  1.634978
2 -0.708137  2.342530  1.053073
4  0.214583 -0.856150 -0.477844

I would like to do both of these operations at the same time (therefore, I am not making an unnecessary copy to do the string label filter). How should I do it?

Pseudocode for what I'm looking for:

df[(df.a > 0) & (df.__index__.isin([0,2,4]))] 
+5
source share
1 answer

You almost had this:

In [11]: df[(df.a > 0) & (df.index.isin([0, 2, 4]))]
Out[11]: 
          a         b         c
0  1.877317  0.109646  1.634978
4  0.214583 -0.856150 -0.477844
+6
source

All Articles