11

DataFrame:

category  value   
A         25  
B         10  
A         15  
B         28  
A         18

Need to Select rows where following conditions are satisfied,
1. category=A and value between 10 and 20
2. categories other than A

1 Answer 1

19

I think you need boolean indexing:

df1 = df[(df['category'] == 'A') & (df['value'].between(10,20))]
print (df1)
  category  value
2        A     15
4        A     18

And then:

df2 = df[(df['category'] != 'A') & (df['value'].between(10,20))]
print (df2)
  category  value
1        B     10

Or:

df3 = df[df['category'] != 'A']
print (df3)
  category  value
1        B     10
3        B     28

EDIT: Join both conditions with | for or, dont forget add () to first conditions.

df1 = df[((df['category'] == 'A') & (df['value'].between(10,20))) | 
         (df['category'] != 'A')]
print (df1)
  category  value
1        B     10
2        A     15
3        B     28
4        A     18
Sign up to request clarification or add additional context in comments.

7 Comments

I need the result in one data frame. What is the efficient way to do it?
I am not sure if understand, all results are in one DataFrame - df1, df2, df3. Can you explain more?
Those two conditions in one query to get the result. Result will have category A within the range and all the other categories data.
Expected df category,value B,10 A,15 B,28 A,18
Please check edited answer - need add |, but first condition need one () more.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.