首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只适用第一个条件

只适用第一个条件
EN

Stack Overflow用户
提问于 2016-12-04 16:02:54
回答 2查看 94关注 0票数 1

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

代码语言:javascript
复制
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()
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-04 16:08:25

我想你需要知道这个(Python运算符优先):

代码语言:javascript
复制
**          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

就你的情况而言:

代码语言:javascript
复制
census_df[(val1 > val2) & ((census_df['REGION']==1) | 
                           (census_df['REGION']==2)) & 
                           (census_df['CTYNAME']=='Washington')]

可能是你要找的?

票数 1
EN

Stack Overflow用户

发布于 2016-12-04 17:26:33

在对所有条件设置parens之后,您的代码:

代码语言:javascript
复制
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)

请注意,您使用的是按位和(&)、按位或(\)。它们有一些不同于布尔和布尔或。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40960572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档