pythonpandasboolean-indexing

Pandas using both row labels and boolean indexing in the same expression


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 boolean 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 via row labels like this:

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 these operations at the same time (So I avoid making an unnecessary copy just to do the row label filter). How would I go about doing it?

Pseudo code for what I am looking for:

df[(df.a > 0) & (df.__index__.isin([0,2,4]))] 

Solution

  • You nearly had it:

    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