在Pandas数据框中对分类特征进行热编码,同时保留从中提取类别(新列名)的列的原始顺序,最佳/最具python风格的方法是什么?在
例如,如果我的数据帧(df0)中有三列:[“Col_continuous”、“Col_categorical”、“Labels”],我使用
df1hot = pd.get_dummies(df0, columns = ["Col_categorical"])
新数据框中新创建的列出现在“标签”列之后。我希望新列位于“Col\u continuous”和“Labels”之间。在
为了健壮性,我希望在处理其他列中任意排序的分类列的数据帧时保持顺序,例如[“Cont1”,“Cat1”,“Cont2”,“Cont3”,“Cat2”,“Labels”],我希望“Cat1”生成的新列位于“Cont1”和“Cont2”之间。假设我已经有了一个变量,比如categoricalCols,这是一个分类特性名称的列表。在
编辑1:由于juanc的评论,将df1hot = pd.get_dummies(df0, columns = ["Col_continuous"])
更改为df1hot = pd.get_dummies(df0, columns = ["Col_categorical"])
。在
编辑2:添加以“为了健壮性,…”开头的段落
我会用这样的方法:
这告诉pandas将
get_dummies
创建的每个列放在df.columns
的中间相关问题 更多 >
编程相关推荐