Reputation: 4199
I need advice to transform a DataFrame df
from
timestamp group v1 v2
0 11/14/2019 00:00:00 g1 0.00 1
1 11/14/2019 00:00:00 g2 0.00 2
to
timestamp new_group v
11/14/2019 00:00:00 g1_v1 0.00
11/14/2019 00:00:00 g1_v2 1
11/14/2019 00:00:00 g2_v1 0.00
11/14/2019 00:00:00 g2_v2 2
The logic is to combine v1
with v2
then make it as a new column as v
, meanwhile, create a new column new_group
which join the original group
value and original column name(v1
or v2
) as its value.
Upvotes: 0
Views: 32
Reputation: 28729
melt the dataframe, combine the new columns created into one using str cat and filter for required columns
res = (df
.melt(['timestamp','group'])
.assign(new_group = lambda x: x.group.str.cat(x.variable,sep="_"))
.filter(['timestamp','new_group','value'])
)
res
timestamp new_group value
0 11/14/2019 00:00:00 g1_v1 0.0
1 11/14/2019 00:00:00 g2_v1 0.0
2 11/14/2019 00:00:00 g1_v2 1.0
3 11/14/2019 00:00:00 g2_v2 2.0
Upvotes: 1