Python Pandas:如何从列表列创建二进制矩阵? [英] Python Pandas: How to create a binary matrix from column of lists?

查看:220
本文介绍了Python Pandas:如何从列表列创建二进制矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python Pandas DataFrame,如下所示:

I have a Python Pandas DataFrame like the following:

      1
0  a, b
1     c
2     d
3     e

a, b是代表用户功能列表的字符串

a, b is a string representing a list of user features

如何将其转换为用户功能的二进制矩阵,如下所示:

How can I convert this into a binary matrix of the user features like the following:

     a    b    c    d    e
0    1    1    0    0    0
1    0    0    1    0    0
2    0    0    0    1    0
3    0    0    0    0    1

我看到了一个类似的问题用熊猫从一列创建布尔矩阵,但该列不包含列表项.

I saw a similar question Creating boolean matrix from one column with pandas but the column does not contain entries which are lists.

我已经尝试过这些方法,有没有办法将两者合并:

I have tried these approaches, is there a way to merge the two:

pd.get_dummies()

pd.get_dummies()

pd.get_dummies(df[1])


   a, b  c  d  e
0     1  0  0  0
1     0  1  0  0
2     0  0  1  0
3     0  0  0  1

df[1].apply(lambda x: pd.Series(x.split()))

df[1].apply(lambda x: pd.Series(x.split()))

      1
0  a, b
1     c
2     d
3     e

也对创建这种类型的二进制矩阵的不同方式感兴趣!

Also interested in different ways to create this type of binary matrix!

感谢您的帮助!

谢谢

推荐答案

我认为您可以使用:

df = df.iloc[:,0].str.split(', ', expand=True)
       .stack()
       .reset_index(drop=True)
       .str.get_dummies()

print df
   a  b  c  d  e
0  1  0  0  0  0
1  0  1  0  0  0
2  0  0  1  0  0
3  0  0  0  1  0
4  0  0  0  0  1

print df.iloc[:,0].str.replace(' ','').str.get_dummies(sep=',')
   a  b  c  d  e
0  1  1  0  0  0
1  0  0  1  0  0
2  0  0  0  1  0
3  0  0  0  0  1

这篇关于Python Pandas:如何从列表列创建二进制矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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