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
474 views
in Technique[技术] by (71.8m points)

python - Using logical operators in building a Pandas DataFrame

I have two snippets of pandas code which I think should be equivalent, but the second one doesn't do what I expect.

# snippet 1
    data = all_data[[((np.isfinite(all_data[self.design_metric][i]) 
                    and all_data['Source'][i] == 2)) 
                    or ((np.isfinite(all_data[self.actual_metric][i]) 
                    and all_data['Source'][i] != 2))
                    for i in range(len(all_data))]]


# snippet 2
    data = all_data[(all_data['Source'] == 2 &
                    np.isfinite(all_data[self.design_metric])) |
                    (all_data['Source'] != 2 &
                    np.isfinite(all_data[self.actual_metric]))]

Each section (e.g. all_data['Source'] == 2 ) does what I expect on its own but it seems that I'm doing something wrong with the logical operators as the final result is coming out with a different result to the list comprehension version.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The & operator binds more tightly than == (or any comparison operator). See the documentation. A simpler example is:

>>> 2 == 2 & 3 == 3
False

This is because it is grouped as 2 == (2 & 3) == 3, and then comparison chaining is invoked. This is what is happening in your case. You need to put parentheses around each comparison.

 data = all_data[((all_data['Source'] == 2) &
                np.isfinite(all_data[self.design_metric])) |
                ((all_data['Source'] != 2) &
                np.isfinite(all_data[self.actual_metric]))]

Note the extra parentheses around the == and != comparisons.


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

...