0 votes
1 view
in Python by (47.8k points)

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

2 Answers

0 votes
by (107k points)

To get rid of that error you should use Values either while creating variable X or while encoding as mentioned above:-

import numpy as np 

import matplotlib.pyplot as plt 

import pandas as pd 

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

0 votes
by (20.3k points)

Here, X is a data frame and it can't be accessed via slice terminology like X[:, 3]. You can access via iloc or X.values. 

However, the way you have constructed X made it a copy... so. you can use values like:

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Sep 11, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...