使用onehot编码时保留列顺序Pandas。去拿假人

2024-09-30 22:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在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:添加以“为了健壮性,…”开头的段落


Tags: columns数据getlabels顺序分类colpd
1条回答
网友
1楼 · 发布于 2024-09-30 22:25:25

我会用这样的方法:

df.columns=['Col_continuous',*[i for i in df.columns if 'Col_categorical' in i], 'Labels']

这告诉pandas将get_dummies创建的每个列放在df.columns的中间

相关问题 更多 >