Reputation: 147
Can't figure out how to reshape my DataFrame into new one by several binary columns value.
Input:
data code a b c
2016-01-07 foo 0 0 0
2016-01-12 bar 0 0 1
2016-01-03 gar 0 1 0
2016-01-22 foo 1 1 0
2016-01-26 bar 1 1 0
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:
data code
a 2016-01-22 foo
a 2016-01-26 bar
b 2016-01-03 gar
b 2016-01-22 foo
b 2016-01-26 bar
c 2016-01-12 bar
Stucked here from the morning, will appreciate help very much !
Upvotes: 1
Views: 82
Reputation: 863291
Use DataFrame.melt
with filtering 1
in boolean indexing
, DataFrame.pop
is used for removing column after filtration:
df = df.melt(['data','code'], var_name='type')
df = df[df.pop('value').eq(1)]
print (df)
data code type
3 2016-01-22 foo a
4 2016-01-26 bar a
7 2016-01-03 gar b
8 2016-01-22 foo b
9 2016-01-26 bar b
11 2016-01-12 bar c
Upvotes: 2