Pandas:使用波浪号运算符返回带有两个过滤器的逆向数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35939552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:51:29  来源:igfitidea点击:

Pandas: Using the tilde operator to return inverse data with two filters

pythonpandas

提问by RDJ

I'm filtering on two DataFrame columns using isin. Aim is to return two distinct DataFrames: One where the filter conditions are met and one where they're not. The DataFrames should be exact opposites, in effect. However I can't seem to use the tilde operator in the way I assumed I could.

我正在使用isin. 目标是返回两个不同的 DataFrame:一个满足过滤条件,另一个不满足。实际上,数据帧应该是完全相反的。但是,我似乎无法以我认为可以的方式使用波浪号运算符。

A reproducible example:

一个可重现的例子:

raw_data = {
    'id': ['s1', 's2', 's1', 's4', 's2', 's5', 's4', 's2'], 
    'car': ['ford', 'bmw', 'ford', 'mazda', 'ford', 'bmw', 'audi', 'bmw']}

df_a = pd.DataFrame(raw_data, columns= ['id', 'car'])

values1 = ['s1', 's2']
values2 = ['bmw', 'ford']
df_a[(df_a['id'].isin(values1)) & (df_a['car'].isin(values2))]

Returns this:

返回这个:

    id  car
0   s1  ford
1   s2  bmw
2   s1  ford
4   s2  ford
7   s2  bmw

Which is correct. But if try to reverse that using:

哪个是正确的。但是,如果尝试使用以下方法扭转该情况:

df_a[~(df_a['id'].isin(values1)) & (df_a['car'].isin(values2))]

df_a[~(df_a['id'].isin(values1)) & (df_a['car'].isin(values2))]

I get:

我得到:

    id  car
5   s5  bmw

Which is not the inverse. I've tried adding a second tilde to the second filter but can't make it work. Where am I going wrong, or is there a better way to do this?

这不是相反的。我试过在第二个过滤器中添加第二个波浪号,但无法使其工作。我哪里出错了,还是有更好的方法来做到这一点?

回答by EdChum

You need additional parentheses:

您需要额外的括号:

In [411]:
df_a[~((df_a['id'].isin(values1)) & (df_a['car'].isin(values2)))]
#     ^                                                        ^
Out[411]:
   id    car
3  s4  mazda
5  s5    bmw
6  s4   audi

What you did was invert only the first condition.

你所做的只是反转第一个条件。