在一些数据集中,一些数据变量用字符串表示,但为了方便处理,往往想要转换为良好的处理格式,此时不必使用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
很成功