假设我有这样一个 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
1条答案
按热度按时间epfja78i1#
用纯种Pandas怎么样?
输出:
原件: