Pandas:按 OR 条件索引行 [英] Pandas: Index rows by an OR condition

查看:69
本文介绍了Pandas:按 OR 条件索引行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤掉数据框中的某些行,这些行允许两列的值的两种组合.例如,列 'A' 和 'B' 可以是 'A' > 0 和 'B' > 0 或 'A' <0 和 'B' <0. 我想过滤的任何其他组合.

I'm trying to filter out certain rows in my dataframe that is allowing two combinations of values for two columns. For example columns 'A' and 'B' can just be either 'A' > 0 and 'B' > 0 OR 'A' < 0 and 'B' < 0. Any other combination I want to filter.

我尝试了以下

df = df.loc[(df['A'] > 0 & df['B'] > 0) or (df['A'] < 0 & df['B'] < 0)]

这给了我一个错误:系列的真值不明确.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all().

我知道这可能是一个非常微不足道的问题,但老实说我找不到任何解决方案,我无法弄清楚我的方法有什么问题.

I know this is probably a very trivial questions but I couldn't find any solution to be honest and I can't figure out what the problem with my approach ist.

推荐答案

您需要一些括号并为 Pandas 设置格式(和/或变成 &/|):

You need some parenthesis and to format for pandas (and/or to become &/|):

df = df[((df['A'] > 0) & (df['B'] > 0)) | ((df['A'] < 0) & (df['B'] < 0))]

请记住这是在做什么 - 您只是在构建一个巨大的 [True, False, True, True] 列表并将其传递到 df 索引中,告诉它根据是否获得 True 来保留每一行或相应列表中的 False.

Keep in mind what this is doing - you're just building a giant list of [True, False, True, True] and passing that into the df index, telling it to keep each row depending on whether it gets a True or a False in the corresponding list.

这篇关于Pandas:按 OR 条件索引行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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