This is the code:

housing_cat1 = X_train[:,[2,7,8,10,11,13,14,15,16,21,22,23,24,25,27,28,29,30,31,32,33,35,39,40,41,42,53,55,57,58,60,63,64,65,73,74,78,79]].reshape(1,-1)

from future_encoders import OneHotEncoder

cat_encoder = OneHotEncoder(sparse=False)                  # Set to True if sparse matrix is needed
housing_cat_1_1hot = cat_encoder.fit_transform(housing_cat)

2 Answers 2


get_dummies function of pandas can also be used for this. Just create a pandas dataframe with your data and subject it to this function. There is no need to list categorical variables:

X_train_df = pandas.DataFrame(data=X_train)
X_train_df_1hot = pandas.get_dummies(X_train_df)

You can specify prefix etc also for new columns is required:

pandas.get_dummies(data, prefix=None, prefix_sep='_', 
     dummy_na=False, columns=None, 
     sparse=False, drop_first=False, 

Data as a list of lists is available with .values attribute which can be converted to a numpy array:

housing_cat_1hot = numpy.array(X_train_df_1hot.values)

What is the shape of housing_cat1, and what is the shape of housing_cat_1hot?

You shouldn't be reshaping to (1, -1). This takes all the data and puts it in one long row.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.