Skip to content Skip to sidebar Skip to footer

Only The First Condition Applied

I am new in Python. I would like to have the following filtering, but only the first condition is applied and the other conditions are ignored. Could you tell me where am I wrong?

Solution 1:

I think you need to know this(Python operators precedence):

**          Exponentiation (raise to the power)
~ + -       Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
* / % //    Multiply, divide, modulo and floor division
+ -         Addition and subtraction
>> <<       Right and left bitwise shift
&           Bitwise 'AND'td>
^ |         Bitwise exclusive `OR' and regular `OR'
<= < > >=   Comparison operators
<> == !=    Equality operators
= %= /= //= -= += *= **=    Assignment operators
is is not   Identity operators
in not in   Membership operators
not or and  Logical operators

For your case:

census_df[(val1 > val2) & ((census_df['REGION']==1) | 
                           (census_df['REGION']==2)) & 
                           (census_df['CTYNAME']=='Washington')]

is probably what you are looking for?


Solution 2:

After putting parens around all your conditions, your code:

return census_df[(val1>val2) & ((census_df['REGION']==1) | (census_df['REGION']==2) & (census_df['CTYNAME'].str.len=='Washington') ) ] 

evaluates as...

(val1>val2)
bitwise and

(census_df['REGION']==2) bitwise and (census_df['CTYNAME'].str.len=='Washington')
bitwise or
(census_df['REGION']==1)

Note that you are using bitwise and (&), bitwise or (|). These have some different behaviors than boolean and, boolean or.


Post a Comment for "Only The First Condition Applied"