pandas OneHotEncoder -一些列的预定义类别?

inkz8wg9  于 2022-12-25  发布在  其他
关注(0)|答案(1)|浏览(102)

假设我有这样一个 Dataframe :

df = pd.DataFrame({"a": [1,2,3], "b": ["d", "d", "d"]})

我想对“a”列和“b”列都进行OneHotEncode,但假设我知道“a”列的类别是什么:{1,2,3,4,5},但我不知道“b”列的类别是什么(并希望自动推断它们)。
如何仅对“b”特性使用默认categories='auto'行为,但传递“a”特性的类别?看起来OneHotEncode不允许这样做:要么为所有特征传入'auto',要么为所有特征传入预定义类别。
我想保留编码器为未来的转换和能力,以处理未知/看不见的类别一样,Sklearn的OHE做的方式。
我尝试传递categories=[[1,2,3,4,5], 'auto']categories=[[1,2,3,4,5], None]categories=[[1,2,3,4,5], []],但它们都出错了。
函数已剪切

def one_hot_encode_categorical_columns(df, columns, categories="auto"):
    ohe = OneHotEncoder(categories=categories, sparse=False, handle_unknown="ignore")
    ohe_df = pd.DataFrame(ohe.fit_transform(df[columns]))
    ohe_df.columns = ohe.get_feature_names_out(columns)
    new_df = pd.concat([df, ohe_df], axis=1)
    return ohe, new_df

df = pd.DataFrame({"a": [1,2,3], "b": ["d", "d", "d"]})

# call function here
epfja78i

epfja78i1#

用纯种Pandas怎么样?

categories = {'a': [1, 2, 3, 4, 5]}

def dummies(s):
    out = pd.get_dummies(s)
    if s.name in categories:
        return out.reindex(columns=categories[s.name], fill_value=0)
    return out

out = pd.concat([dummies(df[x]).add_prefix(f'{x}_') for x in df], axis=1)

输出:

a_1  a_2  a_3  a_4  a_5  b_d
0    1    0    0    0    0    1
1    0    1    0    0    0    1
2    0    0    1    0    0    1

原件:

df.join(out)

   a  b  a_1  a_2  a_3  a_4  a_5  b_d
0  1  d    1    0    0    0    0    1
1  2  d    0    1    0    0    0    1
2  3  d    0    0    1    0    0    1

相关问题