How to Fix: cannot compare a dtyped [float64] array with a scalar of type [bool]


One error you may encounter when using pandas is:

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

This error usually occurs when you attempt to subset a DataFrame based on multiple conditions and fail to place parenthesis around each individual condition.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we create the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'position': ['G', 'G', 'F', 'C', 'G', 'F', 'F', 'C'],
                   'points': [21, 30, 26, 29, 14, 29, 22, 16]})

#view DataFrame
print(df)

  team position  points
0    A        G      21
1    A        G      30
2    A        F      26
3    A        C      29
4    B        G      14
5    B        F      29
6    B        F      22
7    B        C      16

Now suppose we attempt to use the .loc function to only display the rows where the team is equal to ‘A’ and the position is equal to ‘G’:

#attempt to only show rows where team='A' and position='G'
df.loc[df.team == 'A' & df.position == 'G']

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

We receive a ValueError because we didn’t place parenthesis around the individual conditions.

Since the & operator takes precedence over the == operator, pandas fails to interpret this statement in the correct order.

How to Fix the Error

The easiest way to fix this error is to simply add parenthesis around the individual conditions as follows:

#only show rows where team='A' and position='G'
df.loc[(df.team == 'A') & (df.position == 'G')]

	team	position  points
0	A	G	  21
1	A	G	  30

Notice that we don’t receive any ValueError and we are able to successfully subset the DataFrame.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix: columns overlap but no suffix specified
How to Fix: You are trying to merge on object and int64 columns
How to Fix: cannot set a row with mismatched columns

Leave a Reply

Your email address will not be published.