emax
emax

Reputation: 7235

Python: how to reshape a dataframe based on a condition?`

I have a dataframe that looks like the following

df
     Name   Val1   Val2
0    Mark    0      3
1    Mark    2      3
2    Mark    5      6
3    Mark    7      8

I would like to have something like this

df
       Name  Val1_0    Val1_1   Val1_2   Val1_3  Val2_0    Val2_1   Val2_2   Val2_3
0      Mark    0          2       5        7       3         3        6        8

Upvotes: 0

Views: 122

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24314

try via set_index(),reset_index() and unstack():

out=df.set_index('Name',append=True).unstack(0)

Finally :

out.columns=out.columns.map(lambda x:'_'.join(map(str,x)))
out=out.reset_index()

output of out:

    Name    Val1_0  Val1_1  Val1_2  Val1_3  Val2_0  Val2_1  Val2_2  Val2_3
0   Mark    0       2        5        7       3       3       6      8

Upvotes: 2

Related Questions