python-2.7 - 在 Python Pandas 中将此 Word DataFrame 转换为零一矩阵格式 DataFrame

标签 python-2.7 pandas dataframe sklearn-pandas

想要将user_Id和技能dataFrame矩阵转换成零一DataFrame矩阵格式用户及其对应的技能

输入数据框

     user_Id                        skills

0     user1               [java, hdfs, hadoop]
1     user2               [python, c++, c]
2     user3               [hadoop, java, hdfs]
3     user4               [html, java, php]
4     user5               [hadoop, php, hdfs]

所需的输出数据帧

user_Id       java  c   c++     hadoop  hdfs    python  html    php     

user1         1     0   0       1       1       0       0       0
user2         0     1   1       0       0       1       0       0
 user3        1     0   0       1       1       0       0       0
user4         1     0   0       0       0       0       1       1
user5         0     0   0       1       1       0       0       1

最佳答案

您可以joinastype 创建的新 DataFrame如果需要将 lists 转换为 str(否则省略),则通过 strip 删除 []并使用get_dummies :

df = df[['user_Id']].join(df['skills'].astype(str).str.strip('[]').str.get_dummies(', '))
print (df)
  user_Id  c  c++  hadoop  hdfs  html  java  php  python
0   user1  0    0       1     1     0     1    0       0
1   user2  1    1       0     0     0     0    0       1
2   user3  0    0       1     1     0     1    0       0
3   user4  0    0       0     0     1     1    1       0
4   user5  0    0       1     1     0     0    1       0

df1 = df['skills'].astype(str).str.strip('[]').str.get_dummies(', ')
#if necessary remove ' from columns names
df1.columns = df1.columns.str.strip("'")
df = pd.concat([df['user_Id'], df1], axis=1)
print (df)
  user_Id  c  c++  hadoop  hdfs  html  java  php  python
0   user1  0    0       1     1     0     1    0       0
1   user2  1    1       0     0     0     0    0       1
2   user3  0    0       1     1     0     1    0       0
3   user4  0    0       0     0     1     1    1       0
4   user5  0    0       1     1     0     0    1       0

关于python-2.7 - 在 Python Pandas 中将此 Word DataFrame 转换为零一矩阵格式 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44194300/

相关文章:

python - 制作随机电话号码 xxx-xxx-xxxx

python-2.7 - 值错误 : cannot copy sequence with size 5 to array axis with dimension 2

python - 用 Pandas 读取 CSV 并忽略逗号

python - 没有空间的文件中的 Pandas read_csv?

python - 如何提取 DataFrame 的不同对角线?

python - 向 python 子进程发送复杂的 shell 命令

python-3.x - 如何从 pandas 数据框中删除包含前两列组合的行

python - 如何使用 pandas 和 matplotlib.pyplot 在一张图表上绘制数据框中的多个项目?

python - 使用数据帧数据调用函数会出错(无法将系列转换为 <class 'float' >)

arrays - Python 数组附加向量,然后按位置(而不是按元素)对数组的元素求和