【问题标题】:how to join the results of one hot encoding into a dataframe?如何将一个热编码的结果加入数据帧?
【发布时间】:2021-11-14 07:09:44
【问题描述】:

我想在人口普查数据集中执行一次性编码:

https://archive.ics.uci.edu/ml/datasets/census+income

我要执行的列在国家列中,所以我做了以下内容:

import pandas as pd
from sklearn import preprocessing

def abrirArchivo(fileR):
    head=["gt lt 50","age","workclass","fnlwgt","edu","edu-num","mar-sta","occ","rela","race","sex","cap-gain","cap-loss","country","hpw"]
    f=pd.read_csv(fileR,sep=',')
    f.columns=head

    ohe=oneHot(f)
    print (ohe)

def oneHot(f):
    f[["country"]]=pd.get_dummies(f[["country"]])
    return f

但我收到一个错误提示:

ValueError: Columns must be same length as key

当我进行序数编码时,我对以下代码没有任何问题:

pp=preprocessing.OrdinalEncoder()
f[["country"]]=pp.fit_transform(f[["country"]])

我想要将转换后的 ohe(虚拟变量)连接到我原来的 panda 数据框,以便将其用于分类模型。

有什么帮助吗?

【问题讨论】:

  • f.join(pd.get_dummies(f["country"]))?

标签: python pandas


【解决方案1】:

看看pd.get_dummies 返回什么。现在,尝试考虑是否可以将其放入单个列中!不可能吧?

让我来说明一下。假设你有一个 DataFrame

   col1  col2  
0     1  name1   
1     2  name2   

现在,pd.get_dummies(df['col2']) 返回:

     name1  name2
0     0     1
1     1     0

这是一个具有两列列的DataFrame,一列对应col2列中的每个不同值。

如果你尝试这样做

df['col2'] = pd.get_dummies(df['col2'])

您基本上会尝试在单列中安装包含两列的 DataFrame。不可能!这就是ValueError: Columns must be same length as key 的意思


如果您想在df 中返回这些结果,您可以使用merge、concat 或join。许多不同的方式(SO中有很多关于此的问题)。一个例子是:

df = df.join(pd.get_dummies(df['col2'])).drop(columns='col2')

*注意:drop 用于删除原始列。


get_dummies 也有一个columns 参数,可用于创建假人和一步删除原始列:

df = pd.get_dummies(df, columns=['col2'])

注意旧列名变成了新列prefix,由下划线prefix_sep分隔(_):

   col1  col2_name1  col2_name2
0     1           1           0
1     2           0           1

【讨论】:

  • 知道了!谢谢@rafaelc,所以我应该去掉国家列,然后用虚拟值创建一个数据框并加入我的原始数据框?
  • @Little 看看最后一行代码,可能会有帮助!
【解决方案2】:

您可以将在列上应用一个热编码的结果连接到数据帧的其余部分,因此您可以尝试;

f = pd.concat([f, pd.get_dummies(f[["country"]])], axis=1)

这将导致原始数据框带有额外的虚拟列,以删除您应该添加的国家/地区列

f.drop(labels=["country"], axis=1)

【讨论】:

  • 如何去掉国家栏目?因为它仍然出现
  • 要去掉国家列,你应该添加 f.drop(labels=["country"], axis=1)
猜你喜欢
  • 2017-09-21
  • 2018-12-11
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多