每列中有多个值的 DataFrame.如何在主标题下对它们进行单热编码? [英] DataFrame with multiple values in each column. How to one-hot encode them under the main heading?

查看:43
本文介绍了每列中有多个值的 DataFrame.如何在主标题下对它们进行单热编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataFrame,每列中有一个变量列表.我不知道如何对每列中的数据进行单热编码.

I have a DataFrame with a list of variables within each column. I cannot figure out how to One-Hot Encode the data within each column.

In:

lst = [['Red, Blue, Yellow', 'Blue, Green, Yellow', 'Green, Red, Blue'], ['Yellow, Red, Blue', 'Blue, Red, Green', 'Yellow, Blue, Red'], ['Yellow, Red, Green', 'Red, Yellow, Blue', 'Green, Blue, Red']]
    
df = pd.DataFrame(lst, columns =['A', 'B', 'C'], dtype = float)

Out:

        A                     B                        C
Ella    Red, Blue, Yellow     Blue, Green, Yellow      Green, Red, Blue
Mike    Yellow, Red, Blue     Blue, Red, Green         Yellow, Blue, Red
Dave    Yellow, Red, Green    Red, Yellow, Blue        Green, Blue, Red

我希望使用多层列标题来创建它,如下所示:

I am looking to create it with multi-tiered column headings to look like the below:

       A                                 B                               C
       Red    Blue   Green   Yellow      Red    Blue   Green   Yellow    ....
Ella   1      1      0       1           0      1      1       1         ....
Mike   1      1      0       1           1      1      1       0         ....   
Dave   1      0      1       1           1      1      0       1         ....                                                                                                                                                     

我非常感谢您的指导,因为我已经坚持了一段时间!

I would be so grateful for some guidance as I've been stuck on this for a while!

推荐答案

这里有一个方法:

df = df.stack().str.get_dummies(sep=',')
df.columns = df.columns.str.strip()
df = df.stack().groupby(level=[0,1,2]).sum().unstack(level=[1,2])

这篇关于每列中有多个值的 DataFrame.如何在主标题下对它们进行单热编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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