The following expression yields the boolean value True
using pure Python:
6 > 5 > 4
What is the most pythonic way of chaining comparison operators in a Pandas DataFrame similar to the above?
Desired output here is a new column greater
as per example below:
df = pd.DataFrame([[6,5,4],[1,2,3],index=["a"],columns=["foo","bar","baz"])
Comparing two columns works as expected:
df.loc[df.foo > df.bar, "greater"] = "yes"
foo bar baz greater
a 6 5 4 yes
b 1 2 3 NaN
If we try chaining three cols as per the pure Python example:
df.loc[df.foo > df.bar > df.baz, "greater"] = "yes"
This returns the following error. My understanding is we are trying to compare the bool output from first check with an int in col baz
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I can use the following expression but is there a cleaner way similar to the pure Python example?
df.loc[(df.foo > df.bar) & (df.bar > df.baz), "greater"] = "yes"