Nadaa Taiyab Nadaa Taiyab - 1 year ago 76
Python Question

Pandas error - Truth Value of a Series is Ambiguous when using iloc

I am using a pandas dataframe and I am trying to select rows where the

yearID == 2001
and the
team_IDx == 'OAK'
. The
column is of type int and
is an object. Here's the expression I'm using:

mergeddf.loc[(mergeddf['yearID'] == 2001 & mergeddf['teamID_x'] == 'OAK')]

But I keep getting the error:

TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]

I'm a beginner and not even sure how to phrase my question. I've looked at other answers on stack overflow, but they don't make sense to me. What does this error mean? What underlying concepts should I know about to be able to understand it on my own? How do I resolve this?

Answer Source

This is due to the operator precedence of the bitwise operators, which have higher precedence than logical operators. You need another layer of parentheses around each condition:

mergeddf.loc[((mergeddf['yearID'] == 2001) & (mergeddf['teamID_x'] == 'OAK'))]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download