Column names are: ID,1,2,3,4,5,6,7,8,9.
The col values are either 0 or 1
My dataframe looks like this:
JavaScript
x
11
11
1
ID 1 2 3 4 5 6 7 8 9
2
3
1002 0 1 0 1 0 0 0 0 0
4
1003 0 0 0 0 0 0 0 0 0
5
1004 1 1 0 0 0 0 0 0 0
6
1005 0 0 0 0 1 0 0 0 0
7
1006 0 0 0 0 0 1 0 0 0
8
1007 1 0 1 0 0 0 0 0 0
9
1000 0 0 0 0 0 0 0 0 0
10
1009 0 0 1 0 0 0 1 0 0
11
I want the column names in front of the ID where the value in a row is 1.
The Dataframe i want should look like this:
JavaScript
1
12
12
1
ID Col2
2
1002 2 // has 1 at Col(2) and Col(4)
3
1002 4
4
1004 1 // has 1 at col(1) and col(2)
5
1004 2
6
1005 5 // has 1 at col(5)
7
1006 6 // has 1 at col(6)
8
1007 1 // has 1 at col(1) and col(3)
9
1007 3
10
1009 3 // has 1 at col(3) and col(7)
11
1009 7
12
Please help me in this, Thanks in advance
Advertisement
Answer
set_index
+ stack
, stack will dropna by default
JavaScript
1
16
16
1
df.set_index('ID',inplace=True)
2
3
df[df==1].stack().reset_index().drop(0, axis=1)
4
Out[363]:
5
ID level_1
6
0 1002 2
7
1 1002 4
8
2 1004 1
9
3 1004 2
10
4 1005 5
11
5 1006 6
12
6 1007 1
13
7 1007 3
14
8 1009 3
15
9 1009 7
16