I am getting
TypeError: unhashable type: 'slice'
when executing the below code for encoding categorical data in Python. Can anyone please help?
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') y=dataset.iloc[:, 4] X=dataset.iloc[:, 0:4] # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
Slice is not a hashable object, and therefore it cannot be used as a key to a dictionary. To solve this error, specify the appropriate key names for the values you want or use an iterable object like items() and iterate over the items in the dictionary.
This error occurs when trying to hash a list, which is an unhashable object. For example, using a list as a key in a Python dictionary will cause this error since dictionaries only accept hashable data types as a key. The standard way to solve this issue is to cast a list to a tuple, which is a hashable data type.
The Python "TypeError: unhashable type: 'dict'" occurs when we use a dictionary as a key in another dictionary or as an element in a set . To solve the error, use a frozenset instead, or convert the dictionary into a JSON string before using it as a key.
TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can't be hashed.
X
is a dataframe and can't be accessed via slice terminology like X[:, 3]
. You must access via iloc
or X.values
. However, the way you constructed X
made it a copy... so. I'd use values
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset # dataset = pd.read_csv('50_Startups.csv') dataset = pd.DataFrame(np.random.rand(10, 10)) y=dataset.iloc[:, 4] X=dataset.iloc[:, 0:4] # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() # I changed this line X.values[:, 3] = labelencoder_X.fit_transform(X.values[:, 3])
use Values either while creating variable X or while encoding as mentioned above
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset # dataset = pd.read_csv('50_Startups.csv') dataset = pd.DataFrame(np.random.rand(10, 10)) y=dataset.iloc[:, 4].values X=dataset.iloc[:, 0:4].values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With