我是Python的新手。我希望进行以下筛选,但只应用第一个条件,而忽略其他条件。你能告诉我我哪里错了吗?这是我的数据:

import pandas as pd
census_df = pd.read_csv('census.csv')
census_df.head()
census_df
val1=census_df['POPESTIMATE2015']
val2=census_df['POPESTIMATE2014']
def answer_one():
return census_df[val1>val2 & (census_df['REGION']==1 | (census_df['REGION']==2) & (census_df['CTYNAME'].str.len=='Washington') ) ]
answer_one()发布于 2016-12-04 16:08:25
我想你需要知道这个(Python运算符优先):
** 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就你的情况而言:
census_df[(val1 > val2) & ((census_df['REGION']==1) |
(census_df['REGION']==2)) &
(census_df['CTYNAME']=='Washington')]可能是你要找的?
发布于 2016-12-04 17:26:33
在对所有条件设置parens之后,您的代码:
return census_df[(val1>val2) & ((census_df['REGION']==1) | (census_df['REGION']==2) & (census_df['CTYNAME'].str.len=='Washington') ) ] 评估为..。
(val1>val2)按位和 (普查_df‘’REGION‘=2)按位和(census_df'CTYNAME'.str.len=='Washington')bitwise或 (普查_df‘’REGION‘=1)
请注意,您使用的是按位和(&)、按位或(\)。它们有一些不同于布尔和布尔或。
https://stackoverflow.com/questions/40960572
复制相似问题