[Pandas]Dataframe中的多条件切片为什么不能使用and运算符

对于Dataframe中同一列,如果有多个条件,则不能使用and运算符,需要使用&位运算符。示例如下:

import pandas as pd
df = pd.DataFrame({'name':['a','a','b','b'],'classes':[1,2,3,4],'price':[11,22,33,44]})
print(df[(df['price']>11) and (df['price']<44)])

如果需要找到价格在20到40之间的行,则使用上述代码编译器报如下错误:

   Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/wangxxin/miniconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 1576, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

报错的大概意思就是值是模棱两可,不清晰的,系统无法处理。
这个时间,如果把上述最后一句代码调整为:

df.loc[(df['price']>11) & (df['price']<44)]
#就可以输出正确的内容,如下表示:
      name  classes  price
1    a        2     22
2    b        3     33

那么疑问来了,为什么使用and会报错,而使用&不会报错呢?
这个时候需要回归问题的本质:and与&到底有什么区别?
1、and是python中的逻辑运算符;
2、&是python中的位运算符;
例如:
你可以使用and来表示:1 and 2 =2
但是如果二进制的位运算,则是and无法胜算的

#a=60,二进制数为:0011 1100
a = 0b111100
#b=13,二进制数为:0000 1101
b=0b1101
#a&b,按位运算,应该为:0000 1100,bn 也就是下面的值:12
a&b
12

好了,理解完and与&的区别,后,我们再来看

df[(df['price']>11) and (df['price']<44)]

df.loc[(df['price']>11) & (df['price']<44)]

的区别。直接看还是有点不清楚的,再看df[‘price’]>11打印出来看一下,也许就清晰了,结果如下:

df['price']>11
0    False
1     True
2     True
3     True
Name: price, dtype: bool

这样就一目了然了,因为他的值并不是一个数值,而是一个seriers,需要进行按位运算的,所以只能使用&,而不能使用and运算符。

猜你喜欢

转载自blog.csdn.net/wx0628/article/details/87365629