将 one-hot 编码的数据帧列转换为一列

Eis*_*zia 8 python numpy dataframe pandas

在 pandas 数据框中,one-hot 编码的向量以列的形式存在,即:

Rows   A  B  C  D  E

0      0  0  0  1  0
1      0  0  1  0  0
2      0  1  0  0  0
3      0  0  0  1  0
4      1  0  0  0  0
4      0  0  0  0  1
Run Code Online (Sandbox Code Playgroud)

如何通过在python中对它们进行标签编码将这些列转换为一个数据框列?IE:

Rows   A  

0      4 
1      3  
2      2 
3      4 
4      1  
5      5  
Run Code Online (Sandbox Code Playgroud)

还需要建议一些行有多个 1,如何处理这些行,因为我们一次只能有一个类别。

WeN*_*Ben 6

试试 argmax

#df=df.set_index('Rows')

df['New']=df.values.argmax(1)+1
df
Out[231]: 
      A  B  C  D  E  New
Rows                    
0     0  0  0  1  0    4
1     0  0  1  0  0    3
2     0  1  0  0  0    2
3     0  0  0  1  0    4
4     1  0  0  0  0    1
4     0  0  0  0  1    5
Run Code Online (Sandbox Code Playgroud)


ank*_*_91 6

argmax是要走的路,添加另一种使用idxmaxand 的方式get_indexer

df['New'] = df.columns.get_indexer(df.idxmax(1))+1
#df.idxmax(1).map(df.columns.get_loc)+1
print(df)
Run Code Online (Sandbox Code Playgroud)
Rows  A  B  C  D  E   New
                    
0     0  0  0  1  0    4
1     0  0  1  0  0    3
2     0  1  0  0  0    2
3     0  0  0  1  0    4
4     1  0  0  0  0    1
5     0  0  0  0  1    5
Run Code Online (Sandbox Code Playgroud)