将多个coulmn转换为pandas中一列的类别

将多个coulmn转换为pandas中一列的类别,pandas,data-analysis,data-cleaning,one-hot-encoding,data-preprocessing,Pandas,Data Analysis,Data Cleaning,One Hot Encoding,Data Preprocessing,这是使用一种热编码转换的数据集,0表示否,1表示是 数据: ID colour 0 1001 Red 1 1001 Green 2 1001 Orange 3 1002 Blue 4 1002 Yellow 5 1003 Yellow 6 1003 Orange 7 1004 8 1005 Red 9 1005 Yellow 身份证件 红色 蓝色 绿色 黄的 橙色 1001 1. 0

这是使用一种热编码转换的数据集,0表示否,1表示是

数据:

    ID  colour
0   1001    Red
1   1001    Green
2   1001    Orange
3   1002    Blue
4   1002    Yellow
5   1003    Yellow
6   1003    Orange
7   1004    
8   1005    Red
9   1005    Yellow
身份证件 红色 蓝色 绿色 黄的 橙色 1001 1. 0 1. 0 1. 1002 0 1. 0 1. 0 1003 0 0 0 1. 1. 1004 0 0 0 0 0 1005 1. 0 0 1. 0
可以使用
.dot

df.set_index('ID',inplace=True)
res = df.dot(df.columns + ',').str.rstrip(',').str.split(',').explode().reset_index(name='Colour')

res:

    ID  colour
0   1001    Red
1   1001    Green
2   1001    Orange
3   1002    Blue
4   1002    Yellow
5   1003    Yellow
6   1003    Orange
7   1004    
8   1005    Red
9   1005    Yellow
如果您想在
索引7中删除不包含任何内容的元素,请执行以下操作

res = res.replace('', np.nan).dropna()