![](/img/trans.png)
[英]implement custom one-hot-encoding function for sklearn pipeline
[英]One-hot-encoding multiple columns in sklearn and naming columns
我有以下代碼可以對我擁有的 2 列進行單熱編碼。
# encode city labels using one-hot encoding scheme
city_ohe = OneHotEncoder(categories='auto')
city_feature_arr = city_ohe.fit_transform(df[['city']]).toarray()
city_feature_labels = city_ohe.categories_
city_features = pd.DataFrame(city_feature_arr, columns=city_feature_labels)
phone_ohe = OneHotEncoder(categories='auto')
phone_feature_arr = phone_ohe.fit_transform(df[['phone']]).toarray()
phone_feature_labels = phone_ohe.categories_
phone_features = pd.DataFrame(phone_feature_arr, columns=phone_feature_labels)
我想知道的是如何在 4 行中執行此操作,同時在輸出中正確命名列。 也就是說,我可以通過在fit_transform
包含兩個列名稱來創建一個正確的單熱編碼數組,但是當我嘗試命名結果數據fit_transform
的列時,它告訴我索引的形狀之間存在不匹配:
ValueError: Shape of passed values is (6, 50000), indices imply (3, 50000)
對於背景,電話和城市都有 3 個值。
city phone
0 CityA iPhone
1 CityB Android
2 CityB iPhone
3 CityA iPhone
4 CityC Android
你fit_transform
......就像你說的那樣,你可以直接在fit_transform
添加你想要編碼的所有列。
ohe = OneHotEncoder(categories='auto')
feature_arr = ohe.fit_transform(df[['phone','city']]).toarray()
feature_labels = ohe.categories_
然后你只需要執行以下操作:
feature_labels = np.array(feature_labels).ravel()
這使您可以根據需要命名列:
features = pd.DataFrame(feature_arr, columns=feature_labels)
你為什么不看看pd.get_dummies ? 以下是您可以編碼的方法:
df['city'] = df['city'].astype('category')
df['phone'] = df['phone'].astype('category')
df = pd.get_dummies(df)
cat_features = [ "gender", "cholesterol", "gluc", "smoke", "alco" ] data = pd.get_dummies(data, columns = cat_features)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.