Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas how to perform comparison on column

Tags:

python

pandas

I need to find all the rows in which the coulmn two values are in between 1.5 and 3.5. The result I am expecting is row with index 1 and 2. I tried the following code but getting an error.

>>> 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()
>>> 
like image 694
learner Avatar asked Dec 08 '22 13:12

learner


1 Answers

Unfortunately, you can't do chained comparisons with numpy (and therefore pandas). Do instead:

df[(1.5 <= df.two) & (df.two <= 3.5)]
like image 101
Danica Avatar answered Jan 03 '23 01:01

Danica