如何对 pandas 数据框的一列进行一次热编码? [英] How do I one-hot encode one column of a pandas dataframe?

查看:72
本文介绍了如何对 pandas 数据框的一列进行一次热编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对数据帧的一列进行一次热编码.

I'm trying to one-hot encode one column of a dataframe.

enc = OneHotEncoder()
minitable = enc.fit_transform(df["ids"])

但是我得到了

DeprecationWarning:在0.17中弃用数据时传递1d数组 并在0.19中提高ValueError.

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19.

是否有解决方法?

推荐答案

我认为您可以使用

I think you can use get_dummies:

df = pd.DataFrame({'ids':['a','b','c']})

print (df)
  ids
0   a
1   b
2   c

print (df.ids.str.get_dummies())
   a  b  c
0  1  0  0
1  0  1  0
2  0  0  1

如果输入是带有lists的列,则首先转换为str,然后通过[] .str.strip.html"rel =" noreferrer> strip 并调用

If input is column with lists, first cast to str, remove [] by strip and call get_dummies:

df = pd.DataFrame({'ids':[[0,4,5],[4,7,8],[5,1,2]]})

print(df)
         ids
0  [0, 4, 5]
1  [4, 7, 8]
2  [5, 1, 2]

print (df.ids.astype(str).str.strip('[]').str.get_dummies(', '))
   0  1  2  4  5  7  8
0  1  0  0  1  1  0  0
1  0  0  0  1  0  1  1
2  0  1  1  0  1  0  0

这篇关于如何对 pandas 数据框的一列进行一次热编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆