python读取二进制矩阵_Python Pandas:如何从列表列创建二进制矩阵?

I have a Python Pandas DataFrame like the following:

1

0 a, b

1 c

2 d

3 e

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(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()))

1

0 a, b

1 c

2 d

3 e

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

Any help is appreciated!

Thanks

解决方案

I think you can use:

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

EDITED:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值