如何从包含列表的 pandas 列中进行一次编码? [英] How to one-hot-encode from a pandas column containing a list?
本文介绍了如何从包含列表的 pandas 列中进行一次编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将由元素列表组成的pandas列分解为与唯一元素即one-hot-encode
一样多的列(值1
代表行中存在的给定元素,而0
在没有的情况下).
I would like to break down a pandas column consisting of a list of elements into as many columns as there are unique elements i.e. one-hot-encode
them (with value 1
representing a given element existing in a row and 0
in the case of absence).
例如,以数据框 df
Col1 Col2 Col3
C 33 [Apple, Orange, Banana]
A 2.5 [Apple, Grape]
B 42 [Banana]
我想将其转换为:
df
Col1 Col2 Apple Orange Banana Grape
C 33 1 1 1 0
A 2.5 1 0 0 1
B 42 0 0 1 0
我如何使用pandas/sklearn实现这一目标?
How can I use pandas/sklearn to achieve this?
推荐答案
我们还可以使用 sklearn.preprocessing.MultiLabelBinarizer :
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
df = df.join(pd.DataFrame(mlb.fit_transform(df.pop('Col3')),
columns=mlb.classes_,
index=df.index))
结果:
In [77]: df
Out[77]:
Col1 Col2 Apple Banana Grape Orange
0 C 33.0 1 1 0 1
1 A 2.5 1 0 1 0
2 B 42.0 0 1 0 0
这篇关于如何从包含列表的 pandas 列中进行一次编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文