Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对数据帧的一列进行热编码?_Python_Pandas_Scikit Learn - Fatal编程技术网

Python 如何对数据帧的一列进行热编码?

Python 如何对数据帧的一列进行热编码?,python,pandas,scikit-learn,Python,Pandas,Scikit Learn,我试图对数据帧的一列进行热编码 enc = OneHotEncoder() minitable = enc.fit_transform(df["ids"]) 但是我越来越 不推荐使用警告:在0.17中不推荐将1d数组作为数据传递 并将在0.19中增加ValueError 有解决方法吗?我认为您可以使用: 编辑: 如果输入是带有列表的列,则首先转换为str,删除[],然后调用: minitable=enc.fit_transform(df[[“ids”]])在没有警告的情况下工作吗?我需要转换为

我试图对数据帧的一列进行热编码

enc = OneHotEncoder()
minitable = enc.fit_transform(df["ids"])
但是我越来越

不推荐使用警告:在0.17中不推荐将1d数组作为数据传递 并将在0.19中增加ValueError

有解决方法吗?

我认为您可以使用:

编辑:

如果输入是带有
列表的列
,则首先转换为
str
,删除
[]
,然后调用:


minitable=enc.fit_transform(df[[“ids”]])
在没有警告的情况下工作吗?我需要转换为字符串。可以使用整数而不进行强制转换吗?问题是使用
print(df.ids.str.get\u dummies().astype(str))
?当ids是一个整数列表时,上面的代码将不起作用。尽管这是堆栈溢出,但
get\u 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
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