jfi*_*ive 1 python sparse-matrix dataframe pandas binary-matrix
我有一个Python Pandas DataFrame,如下所示:
1
0 a, b
1 c
2 d
3 e
Run Code Online (Sandbox Code Playgroud)
a, b 是代表用户功能列表的字符串
如何将其转换为用户功能的二进制矩阵,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
我看到了一个类似的问题,即用熊猫从一列创建布尔矩阵,但是该列不包含列表项。
我已经尝试过这些方法,有没有办法将两者合并:
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
Run Code Online (Sandbox Code Playgroud)
df[1].apply(lambda x: pd.Series(x.split()))
1
0 a, b
1 c
2 d
3 e
Run Code Online (Sandbox Code Playgroud)
也有兴趣以不同方式创建这种类型的二进制矩阵!
任何帮助表示赞赏!
谢谢
我认为您可以使用:
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
Run Code Online (Sandbox Code Playgroud)
编辑:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3240 次 |
| 最近记录: |