如何从熊猫数据框中反转虚拟变量

Car*_*cca 4 python dataframe pandas

我想用虚拟变量反转数据框。例如,

来自 df_input:

Course_01 Course_02 Course_03 
  0           0         1 
  1           0         0 
  0           1         0 
Run Code Online (Sandbox Code Playgroud)

到 df_output

   Course
0 03
1 01
2 02
Run Code Online (Sandbox Code Playgroud)

我一直在查看Reconstruct a categorical variable from dummys in pandas提供的解决方案,但它没有用。请,任何帮助将不胜感激。

非常感谢,最好的问候,卡罗

Flo*_*oor 5

我们可以使用wide_to_long,然后选择不等于零的行,即

ndf = pd.wide_to_long(df, stubnames='T_', i='id',j='T')

      T_
id  T     
id1 30   0
id2 30   1
id1 40   1
id2 40   0

not_dummy = ndf[ndf['T_'].ne(0)].reset_index().drop('T_',1)

   id   T
0  id2  30
1  id1  40
Run Code Online (Sandbox Code Playgroud)

根据您的编辑更新:

ndf = pd.wide_to_long(df.reset_index(), stubnames='T_',i='index',j='T')

not_dummy = ndf[ndf['T_'].ne(0)].reset_index(level='T').drop('T_',1)

        T
index    
1      30
0      40
Run Code Online (Sandbox Code Playgroud)