You you are almost there... Like you said you can add all the columns you want to encode in fit_transform directly.
ohe = OneHotEncoder(categories='auto')
feature_arr = ohe.fit_transform(df[['phone','city']]).toarray()
feature_labels = ohe.categories_
And then you just need to do the following:
feature_labels = np.array(feature_labels).ravel()
Which enables you to name your columns like you wanted:
features = pd.DataFrame(feature_arr, columns=feature_labels)
Answer from MaximeKan on Stack OverflowYou you are almost there... Like you said you can add all the columns you want to encode in fit_transform directly.
ohe = OneHotEncoder(categories='auto')
feature_arr = ohe.fit_transform(df[['phone','city']]).toarray()
feature_labels = ohe.categories_
And then you just need to do the following:
feature_labels = np.array(feature_labels).ravel()
Which enables you to name your columns like you wanted:
features = pd.DataFrame(feature_arr, columns=feature_labels)
this solution gives column names same as in pd.get_dummies(), what is useful IMO
labels = ['Sex', 'Embarked', 'Pclass']
categorical_data = data[labels]
ohe = OneHotEncoder(categories='auto')
feature_arr = ohe
.fit_transform(categorical_data)
.toarray()
ohe_labels = ohe.get_feature_names(labels)
features = pd.DataFrame(
feature_arr,
columns=ohe_labels)
LabelEncoder is not made to transform the data but the target (also known as labels) as explained here. If you want to encode the data you should use OrdinalEncoder.
If you really need to do it this way:
categorical_cols = ['a', 'b', 'c', 'd']
from sklearn.preprocessing import LabelEncoder
# instantiate labelencoder object
le = LabelEncoder()
# apply le on categorical feature columns
data[categorical_cols] = data[categorical_cols].apply(lambda col: le.fit_transform(col))
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder()
#One-hot-encode the categorical columns.
#Unfortunately outputs an array instead of dataframe.
array_hot_encoded = ohe.fit_transform(data[categorical_cols])
#Convert it to df
data_hot_encoded = pd.DataFrame(array_hot_encoded, index=data.index)
#Extract only the columns that didnt need to be encoded
data_other_cols = data.drop(columns=categorical_cols)
#Concatenate the two dataframes :
data_out = pd.concat([data_hot_encoded, data_other_cols], axis=1)
Otherwise:
I suggest you to use pandas.get_dummies if you want to achieve one-hot-encoding from raw data (without having to use OrdinalEncoder before) :
#categorical data
categorical_cols = ['a', 'b', 'c', 'd']
#import pandas as pd
df = pd.get_dummies(data, columns = categorical_cols)
You can also use drop_first argument to remove one of the one-hot-encoded columns, as some models require.
You can do dummy encoding using Pandas in order to get one-hot encoding as shown below:
import pandas as pd
# Multiple categorical columns
categorical_cols = ['a', 'b', 'c', 'd']
pd.get_dummies(data, columns=categorical_cols)
If you want to do one-hot encoding using sklearn library, you can get it done as shown below:
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder()
transformed_data = onehotencoder.fit_transform(data[categorical_cols])
# the above transformed_data is an array so convert it to dataframe
encoded_data = pd.DataFrame(transformed_data, index=data.index)
# now concatenate the original data and the encoded data using pandas
concatenated_data = pd.concat([data, encoded_data], axis=1)
If a single column has more than 500 categories, the aforementioned way of one-hot encoding is not a good approach. In this case, we can do one-hot encoding for the top 10 or 20 categories that are occurring most for a particular column. A sample code is shown below:
categorical_cols = ['a', 'b', 'c', 'd']
# Let's say we have a column 'b' which has more than 500 categories.
# Find the top 10 most frequent categories for column 'b'
data.b.value_counts().sort_values(ascending = False).head(20)
# make a list of the most frequent categories of the column
top_10_occurring_cat = [cat for cat in data.b.value_counts().sort_values(ascending = False).head(10).index]
# now make the 10 binary variables
for cat in top_10_occurring_cat:
data[cat] = np.where(data['b'] == cat, 1, 0) # whenever data['b'] == cat replace it with 1 else 0
# This is done for one categorical column, similarly you can repeat for all categorical columns
python - OneHotEncoding multiple columns in dataset at once - Stack Overflow
pandas - OneHotEncoder Multiple Columns - Stack Overflow
python - Using OneHotEncoder in multiple columns with repetead categories amongst columns? - Stack Overflow
python - OneHotEncoder - multiple columns at once - Stack Overflow
import pandas as pd
df = pd.DataFrame({'name': ['Manie', 'Joyce', 'Ami'],
'Org': ['ABC2', 'ABC1', 'NSV2'],
'Dept': ['Finance', 'HR', 'HR']
})
df_2 = pd.get_dummies(df,drop_first=True)
test:
print(df_2)
Dept_HR Org_ABC2 Org_NSV2 name_Joyce name_Manie
0 0 1 0 0 1
1 1 0 0 1 0
2 1 0 1 0 0
UPDATE regarding your error with pd.get_dummies(X, columns =[1:]:
Per the documentation page, the columns parameter takes "Column Names". So the following code would work:
df_2 = pd.get_dummies(df, columns=['Org', 'Dept'], drop_first=True)
output:
name Org_ABC2 Org_NSV2 Dept_HR
0 Manie 1 0 0
1 Joyce 0 0 1
2 Ami 0 1 1
If you really want to define your columns positionally, you could do it this way:
column_names_for_onehot = df.columns[1:]
df_2 = pd.get_dummies(df, columns=column_names_for_onehot, drop_first=True)
I use my own template for doing that:
from sklearn.base import TransformerMixin
import pandas as pd
import numpy as np
class DataFrameEncoder(TransformerMixin):
def __init__(self):
"""Encode the data.
Columns of data type object are appended in the list. After
appending Each Column of type object are taken dummies and
successively removed and two Dataframes are concated again.
"""
def fit(self, X, y=None):
self.object_col = []
for col in X.columns:
if(X[col].dtype == np.dtype('O')):
self.object_col.append(col)
return self
def transform(self, X, y=None):
dummy_df = pd.get_dummies(X[self.object_col],drop_first=True)
X = X.drop(X[self.object_col],axis=1)
X = pd.concat([dummy_df,X],axis=1)
return X
And for using this code just put this template in current directory with filename let's suppose CustomeEncoder.py and type in your code:
from customEncoder import DataFrameEncoder
data = DataFrameEncoder().fit_transormer(data)
And all the object type data removed, Encoded, removed first and joined together to give the final desired output.
PS: That the input file to this template is Pandas Dataframe.