close

[Solved] Python “TypeError: unhashable type: ‘slice'” for encoding categorical data

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python “TypeError: unhashable type: ‘slice'” for encoding categorical data 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 Python “TypeError: unhashable type: ‘slice'” for encoding categorical data Error Occurs?

Today I get the following error Python “TypeError: unhashable type: ‘slice'” for encoding categorical data in python.

How To Solve Python “TypeError: unhashable type: ‘slice'” for encoding categorical data Error ?

  1. How To Solve Python “TypeError: unhashable type: 'slice'” for encoding categorical data Error ?

    To Solve Python “TypeError: unhashable type: 'slice'” for encoding categorical data Error 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

  2. Python “TypeError: unhashable type: 'slice'” for encoding categorical data

    To Solve Python “TypeError: unhashable type: 'slice'” for encoding categorical data Error 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

Solution 1

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])

Solution 2

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])

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