Fluxy
Fluxy

Reputation: 2978

TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

I have this pandas DataFrame df:

         Col1    Col2
Col0
True     False   False
False    False   False
False    True    False
False    True    False
False    False   False

I want to substitute False with No and True with Yes:

bool_to_str = {'False': 'No', 'True': 'Si'}
df.replace({
        'Col1': bool_to_str,
        'Col2': bool_to_str
    }, inplace=True)


df.dtypes:

Col1   bool
Col2   bool
dtype: object

But get the following error:

TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

I checked that all columns of df do not contain arrays, only boolean values- For example, df["Col1"].values[0] returns False.

Upvotes: 4

Views: 2271

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

The keys of your bool_to_str dictionary are not booleans, but strings. You should define the dictionary as:

bool_to_str = {False: 'No', True: 'Si'}

For example:

>>> df
    Col1   Col2
0  False  False
1  False  False
2   True  False
3   True  False
4  False  False
>>> df.replace({'Col1': {False: 'No', True: 'Si'}})
  Col1   Col2
0   No  False
1   No  False
2   Si  False
3   Si  False
4   No  False

Upvotes: 2

Related Questions