1# Basic syntax:
2df_onehot = pd.get_dummies(df, columns=['col_name'], prefix=['one_hot'])
3# Where:
4# - get_dummies creates a one-hot encoding for each unique categorical
5# value in the column named col_name
6# - The prefix is added at the beginning of each categorical value
7# to create new column names for the one-hot columns
8
9# Example usage:
10# Build example dataframe:
11df = pd.DataFrame(['sunny', 'rainy', 'cloudy'], columns=['weather'])
12print(df)
13 weather
140 sunny
151 rainy
162 cloudy
17
18# Convert categorical weather variable to one-hot encoding:
19df_onehot = pd.get_dummies(df, columns=['weather'], prefix=['one_hot'])
20print(df_onehot)
21 one_hot_cloudy one_hot_rainy one_hot_sunny
220 0 0 1
231 0 1 0
242 1 0 0
1from sklearn.preprocessing import LabelEncoder
2
3le = LabelEncoder()
4companydata.ShelveLoc = le.fit_transform(companydata.ShelveLoc)
1
2obj_df["body_style"] = obj_df["body_style"].astype('category')
3obj_df.dtypes
4
5obj_df["body_style_cat"] = obj_df["body_style"].cat.codes
6obj_df.head()
7