gpt4 book ai didi

python - 使用 Pandas 执行一次热编码

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:25 24 4
gpt4 key购买 nike

我正在 Pandas 中制作以下数据框:

df=pd.DataFrame(np.array([20,"admin","France",
25,"worker","Italy",
45,"admin","Norway",
30,"sec","EEUU",
25,"law",np.NaN,
30,"sec","France"]

).reshape(6,3))
df.columns=["age","job","country"]

我想执行一次热编码,但不使用 get_dummies 功能,而是想使用 OneHotEncoder。所以我编写了以下代码:

def oneHotEncoding(df):
ohe=preprocessing.OneHotEncoder(dtype=np.int,sparse=True,handle_unknown="ignore")
values=pd.DataFrame(ohe.fit_transform(df[["country"]]).toarray())
df=pd.concat([df,values],axis=1)
df=df.drop(["country"],1)
print(df)

问题是当我得到结果时,我得到类似的东西:

   age  job    0  1  2  3  4
0 20 admin 0 1 0 0 0
1 25 worker 0 0 1 0 0
2 45 admin 0 0 0 1 0
3 30 sec 1 0 0 0 0
4 25 law 0 0 0 0 1
5 30 sec 0 1 0 0 0

我希望在结果的列中出现类似 country_france、country_italy 等的内容,我尝试了以下代码:

values=pd.DataFrame(ohe.fit_transform(df[["country"]]).toarray(),columns=["country_"+str(int(i)) for i in range(df.shape[1])])

但它没有给我正确的结果。

此外,nan 值仍然被视为一个国家,它应该只有 0。

我该如何解决这些问题?我已经测试了在这里发现的不同可能性,但没有任何帮助。

谢谢

最佳答案

如果您坚持使用 OneHotEncoder,您的问题是您的稀疏矩阵没有列数据,在您的示例中属性实际上存储在 ohe 上。

使用 fit_transform 后,您可以从 OneHotEncoder 上的 categories_ 属性访问类别


ohe = preprocessing.OneHotEncoder(dtype=np.int,sparse=True,handle_unknown="ignore")

data = ohe.fit_transform(df[['country']])

values = pd.DataFrame(data.A, columns='country_' + ohe.categories_[0])

   country_EEUU  country_France  country_Italy  country_Norway  country_nan
0 0 1 0 0 0
1 0 0 1 0 0
2 0 0 0 1 0
3 1 0 0 0 0
4 0 0 0 0 1
5 0 1 0 0 0

关于python - 使用 Pandas 执行一次热编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57422194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com