pandas :使用波浪号运算符通过两个过滤器返回逆数据 [英] Pandas: Using the tilde operator to return inverse data with two filters

查看:107
本文介绍了 pandas :使用波浪号运算符通过两个过滤器返回逆数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

可复制的示例:

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))]

返回此:

    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))]

我得到:

    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?

推荐答案

您需要附加括号:

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.

这篇关于 pandas :使用波浪号运算符通过两个过滤器返回逆数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆