在有些数据集中,有些数据变量用字符串表示,但为了方便处理,往往想转换为好处理的格式,这时候不一定要用one hot进行编码,也可以直接转成整数:
test_df["xx"] = pd.factorize(test_df["xx"])[0].astype(int)
但是这样映射的数字是从0开始的,如果有初始要求,可以对映射结果加上某个值,例如,把从0开始变为从15开始:
test_df["xx"] = test_df["xx"].add(15)
效果gift_cards["user_id"] = pd.factorize(gift_cards["user_id"])[0].astype(int):
user_id item_id ratings time 0 B001GXRQW0 APV13CM0919JD 1.0 1229644800 1 B001GXRQW0 A3G8U1G1V082SN 5.0 1229472000 2 B001GXRQW0 A11T2Q0EVTUWP 5.0 1229472000 3 B001GXRQW0 A9YKGBH3SV22C 5.0 1229472000 4 B001GXRQW0 A34WZIHVF3OKOL 1.0 1229472000 ... ... ... ... ... 147189 B01H5PPJT4 A2K9WVQW9TLWNK 5.0 1536969600 147190 B01H5PPJT4 A149ALSR6TPGF7 4.0 1536278400 147191 B01H5PPJT4 A2Q066NZCQSCOR 5.0 1535500800 147192 B01H5PPJT4 A1KJLWCW7XBS8I 5.0 1534550400 147193 B01H5PPJT4 ANABUB0FRZXRM 5.0 1534204800
user_id item_id ratings time 0 0 APV13CM0919JD 1.0 1229644800 1 0 A3G8U1G1V082SN 5.0 1229472000 2 0 A11T2Q0EVTUWP 5.0 1229472000 3 0 A9YKGBH3SV22C 5.0 1229472000 4 0 A34WZIHVF3OKOL 1.0 1229472000 ... ... ... ... ... 147189 858 A2K9WVQW9TLWNK 5.0 1536969600 147190 858 A149ALSR6TPGF7 4.0 1536278400 147191 858 A2Q066NZCQSCOR 5.0 1535500800 147192 858 A1KJLWCW7XBS8I 5.0 1534550400 147193 858 ANABUB0FRZXRM 5.0 1534204800
很成功