Can’t figure out how to reshape my DataFrame into new one by several binary columns value.
Input:
JavaScript
x
8
1
data code a b c
2
3
2016-01-07 foo 0 0 0
4
2016-01-12 bar 0 0 1
5
2016-01-03 gar 0 1 0
6
2016-01-22 foo 1 1 0
7
2016-01-26 bar 1 1 0
8
I want to reshape by binary values, i.e. column a/b/c, if their value == 1, I need every time new column with all data.
Expected output:
JavaScript
1
8
1
data code
2
a 2016-01-22 foo
3
a 2016-01-26 bar
4
b 2016-01-03 gar
5
b 2016-01-22 foo
6
b 2016-01-26 bar
7
c 2016-01-12 bar
8
Stucked here from the morning, will appreciate help very much !
Advertisement
Answer
Use DataFrame.melt
with filtering 1
in boolean indexing
, DataFrame.pop
is used for removing column after filtration:
JavaScript
1
11
11
1
df = df.melt(['data','code'], var_name='type')
2
df = df[df.pop('value').eq(1)]
3
print (df)
4
data code type
5
3 2016-01-22 foo a
6
4 2016-01-26 bar a
7
7 2016-01-03 gar b
8
8 2016-01-22 foo b
9
9 2016-01-26 bar b
10
11 2016-01-12 bar c
11