7

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]))] 
2
  • You can try with df.ix[df['a'] > 0, [0,2,4]]
    – nemesv
    Feb 6, 2013 at 9:09
  • For the above example data frame that would throw an exception, since this is trying to pull the 0, 2nd and 4th columns, and we only have 3 columns.
    – jason
    Feb 6, 2013 at 9:14

2 Answers 2

6

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
1
  • Indeed! Almost! Right there!
    – jason
    Feb 6, 2013 at 9:26
0
df.loc[functools.reduce(lambda x, y : x & y, [df.a>0, df.index.isin([0, 2, 4])])]
1
  • Please avoid code only answer; Provide an explanation to what's hapenning in here. Jun 29 at 14:01

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.