Home > Mobile >  How to unstack a crosstable as fast as possible
How to unstack a crosstable as fast as possible

Time:03-30

Here's my dataset:

Id     Column_A    Column_B
1             1           0
2             1           1
3             0           1
4             0           0

Here's my expected output:

Id     Column
1      Column_A
2      Column_B
2      Column_B
3      Column_C 

CodePudding user response:

Use DataFrame.melt with DataFrame.query by condition - here not equal 0 and remove helper column value:

df = df.melt('Id', var_name='Column').query('value != 0').drop('value',1)
print (df)
   Id    Column
0   1  Column_A
1   2  Column_A
5   2  Column_B
6   3  Column_B
  • Related