Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

python - Why does my pandas filters work in separate steps but not in one command?

I'm having problems filtering my pandas dataframe in one command. For instance, the following multi-step filter works perfectly:

check2020 = check[check['effyear'] == '2020']
check2020_can = check2020[check2020['canceled'] == 'Y']
check2020_can_6 = check2020_can[check2020_can['decile'] == 6]
check2020_can_6_p_s = check2020_can_6[(check2020_can_6['usage'] == 'P') | (check2020_can_6['usage'] == 'S')]

But if I were to do the following:

check[(check['effyear'] == '2020') & (check['canceled'] == 'Y') & (check['decile'] == 6) & (check['usage'] == 'P') | (check['usage'] == 'S')]

Then I get 30,000 more observations that do not all follow the filter. Is the all in one filter not structured correclty?

question from:https://stackoverflow.com/questions/65941981/why-does-my-pandas-filters-work-in-separate-steps-but-not-in-one-command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe you need extra pair of parenthesis:

check[(check['effyear'] == '2020') & 
      (check['canceled'] == 'Y') & 
      (check['decile'] == 6) & 
      ((check['usage'] == 'P') | (check['usage'] == 'S')) # () here
     ]

Also, use isin for better syntax:

check[(check['effyear'] == '2020') & 
      (check['canceled'] == 'Y') & 
      (check['decile'] == 6) & 
      check['usage'].isin(['P', 'S'])  # this
     ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...