我的資料框中的一列中有 10 個唯一值。例如下面是資料框
df['categories'].unique()
輸出是:
Electronic
Computers
Mobile Phone
Router
Food
我想用 1 替換“電子”,用 2 替換“計算機”,用 3 替換“手機”,用 4 替換“路由器”,用 5 替換“食物”。預期的輸出必須是
df['categories'].unique()
預期輸出:
1
2
3
4
5
我嘗試回圈 df['categories'].unique(),但我無法做到這一點。誰能幫我這個?
uj5u.com熱心網友回復:
這將起作用:
new_vals = {'Electronic': 1, 'Computers' : 2, 'Mobile Phone' : 3, 'Router' : 4 , 'Food' : 5}
df = df.replace({'categories': new_vals})
uj5u.com熱心網友回復:
你可以試試這個:
df['categories'] = df['categories'].astype('category').cat.codes
uj5u.com熱心網友回復:
scikit-learn提供類似的功能。
當您嘗試構建預測模型并且代碼不起作用時,此方法是最佳選擇:
例如,這對您來說無關緊要:“計算機”類別將獲得“1”或“2”或“5”的代碼。
from sklearn.preprocessing import OrdinalEncoder
enc = OrdinalEncoder()
df['categories'] = enc.fit_transform(X=df[['categories']]).astype('int')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438679.html
標籤:Python python-3.x 熊猫 数据框 for循环
