Creating a DataFrame in Pandas using logical and operator

Viewed 4226

I have a pandas Datarame with some columns and I first wanted to print only those rows whose values in a particular column is less than a certain value. So I did:

df[df.marks < 4.5]

It successfully created the dataframe, now I want to add only those columns whose values are in a certain range, so I tried this:

df[(df.marks < 4.5 and df.marks > 4)]

but it's giving me an error:

712         raise ValueError("The truth value of a {0} is ambiguous. "    
713                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 714                          .format(self.__class__.__name__))
715 
716     __bool__ = __nonzero__    
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().

How do I resolve this? And initially I also thought that it would iterate through all the rows and check the truth value and then add the row in the dataframe, but it seems like this isn't the case, if so how does it add the row in the dataframe?

3 Answers
Related