如何对 pandas 列中的列表执行“一次热编码"? [英] How do I perform One Hot Encoding on lists in a pandas column?
本文介绍了如何对 pandas 列中的列表执行“一次热编码"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个数据框,其中的一列是一个列表(值和长度未知),例如:
Suppose I have a dataframe of which one column is a list (of a unknown values and length) for example:
df = pd.DataFrame(
{'messageLabels': [['Good', 'Other', 'Bad'],['Bad','Terrible']]}
)
我遇到了这个解决方案,但这不是我想要的. 如何最好地提取包含多列列表或元组的Pandas列
I came across this solution but it isnt what I am looking for. How best to extract a Pandas column containing lists or tuples into multiple columns
理论上,最终的df看起来像
in theory the resulting df would look like
messageLabels | Good| Other| Bad| Terrible
--------------------------------------------------------
['Good', 'Other', 'Bad'] | True| True |True| False
--------------------------------------------------------
['Bad','Terrible'] |False|False |True| True
见上文
推荐答案
另一种方法是使用apply和Series构造函数:
Another way is to use the apply and the Series constructor:
In [11]: pd.get_dummies(df.messageLabels.apply(lambda x: pd.Series(1, x)) == 1)
Out[11]:
Good Other Bad Terrible
0 True True True False
1 False False True True
其中
In [12]: df.messageLabels.apply(lambda x: pd.Series(1, x))
Out[12]:
Good Other Bad Terrible
0 1.0 1.0 1.0 NaN
1 NaN NaN 1.0 1.0
要获得所需的输出,请执行以下操作:
To get your desired output:
In [21]: res = pd.get_dummies(df.messageLabels.apply(lambda x: pd.Series(1, x)) == 1)
In [22]: df[res.columns] = res
In [23]: df
Out[23]:
messageLabels Good Other Bad Terrible
0 [Good, Other, Bad] True True True False
1 [Bad, Terrible] False False True True
这篇关于如何对 pandas 列中的列表执行“一次热编码"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文