python – pandas如何在列上执行比较

我需要找到coulmn两个值在1.5和3.5之间的所有行.我期待的结果是索引1和2的行.我尝试了以下代码,但收到错误.

>>> d = {'one' : [1., 2., 3., 4.],
...  'two' : [4., 3., 2., 1.],
... 'three':['a','b','c','d']}
>>> d
{'three': ['a', 'b', 'c', 'd'], 'two': [4.0, 3.0, 2.0, 1.0], 'one': [1.0, 2.0, 3.0, 4.0]}
>>> DataFrame(d)
   one three  two
0    1     a    4
1    2     b    3
2    3     c    2
3    4     d    1
>>> df = DataFrame(d)
>>> df[1.5 <= df['two'] <= 3.5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 

解决方法:

不幸的是,你不能用numpy(因此还有pandas)进行链式比较.改为:

df[(1.5 <= df.two) & (df.two <= 3.5)]

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...