close

[Solved] Cannot compare types ‘ndarray(dtype=int64)’ and ‘str’

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Cannot compare types ‘ndarray(dtype=int64)’ and ‘str’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Cannot compare types ‘ndarray(dtype=int64)’ and ‘str’ Error Occurs?

Today I get the following error Cannot compare types ‘ndarray(dtype=int64)’ and ‘str’ in python.

How To Solve Cannot compare types ‘ndarray(dtype=int64)’ and ‘str’ Error ?

  1. How To Solve Cannot compare types 'ndarray(dtype=int64)' and 'str' Error ?

    To Solve Cannot compare types 'ndarray(dtype=int64)' and 'str' Error I was facing the same issue and what worked for me was converting the datatype of the feature to an object type.

  2. Cannot compare types 'ndarray(dtype=int64)' and 'str'

    To Solve Cannot compare types 'ndarray(dtype=int64)' and 'str' Error I was facing the same issue and what worked for me was converting the datatype of the feature to an object type.

Solution 1

Some of you string you passed to replace with an (int)value, actually is an ndarray of int64 values. You only have int64( here actually ndarray(dtype=int64)) type data in this column. See document pandas.Dataframe.replace(). replace() try to seek and compare them with the str values you passed.

df["Buying_Price"]=df["Buying_Price"].replace({"vhigh":4})

find all "vhigh" value and compare with the value currently contains, the replace it with 4. At the comparing it fails as try to compare str data with int64 ('ndarray(dtype=int64)')

A brief example to simulate this:

import pandas as pd
import numpy as np

a = np.array([1])
df = pd.DataFrame({"Maintanance_price": a})
df["Maintanance_price"] = df["Maintanance_price"].replace({"a":1})

print(df)

Out:

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

Solution 2

I was facing the same issue and what worked for me was converting the datatype of the feature to an object type.

   train['Some_feature']=train.Some_feature.astype(object)

Hope it helps.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read