根据多列条件过滤DataFrame

根据多列条件过滤DataFrame

本文介绍了根据多列条件过滤DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何使用'and'过滤数据框?换句话说,如果我有一个名为m的数据框,并且具有a,b,c,d,e列,我将如何返回b列中的值大于120且c列中的值等于7.3的所有行?

How would I filter a dataframe using 'and' ? In other words, if I have a dataframe named m and it has columns a,b,c,d,e, how would i return all rows where the values in column b are greater than 120 and the vales in column c = 7.3 ?

我尝试了这个,但是出现错误:

I tried this but I'm getting an error:

print(m [m ['b']> 120,m ['c'] == 7.3])

print(m[m['b'] >120, m['c'] ==7.3])

推荐答案

要扩展GoBrewers14的答案,您需要环绕括号以克服在python中对运算符求值的顺序.

To expand on GoBrewers14's answer, you need to wrap around parenthesis to overcome the order of evaluation of the operators in python.

例如,下一条语句失败:

For example, the next statement fails:

In [3]: 1 > 0 & 'a' < 'b'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-5d58a7b0bade> in <module>()
----> 1 1 > 0 & 'a' < 'b'

TypeError: unsupported operand type(s) for &: 'int' and 'str'

因为python首先计算0 & 'a'.这就是为什么您需要用括号将语句包装起来才有意义:

because python evaluates first 0 & 'a'. That's why you need to wrap the statements with parenthesis to make sense:

In [4]: (1 > 0) & ('a' < 'b')
Out[4]: True

简而言之,您正在寻找:

In short, you are looking for:

m[(m['b'] > 120) & (m['c'] == 7.3)]

这篇关于根据多列条件过滤DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:56