我想用虚拟变量反转数据框。例如,
来自 df_input:
Course_01 Course_02 Course_03
0 0 1
1 0 0
0 1 0
到 df_output
Course
0 03
1 01
2 02
我一直在查看 Reconstruct a categorical variable from dummies in pandas 提供的解决方案但它没有用。请,任何帮助将不胜感激。
非常感谢, 此致, 卡罗
最佳答案
我们可以使用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
根据您的修改进行更新:
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
关于python - 如何从 Pandas 数据框中反转虚拟变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47694550/