Transforming pandas dataframe : un pivot

Viewed 55

I have the following dataframe :

commune nuance_1    votes_1 nuance_2    votes_2 nuance_3    votes_3
A       X           12      Y           20      Z           5 
B       X           10      Y            5      
C       Z            7      X            2  

and I would like to obtain after transformation :

commune nuance  votes
A       X       12
A       Y       20
A       Z        5
B       X       10
B       Y        5
C       Z        7
C       X        2

Is there a way to do this ( sort of un pivot ) ?

1 Answers

You can use pd.wide_to_long here:

out = (pd.wide_to_long(df,['nuance','votes'],'commune','j',sep='_')
       .dropna(how='all').sort_index(0).droplevel(1).reset_index())

print(out)

 commune nuance  votes
0       A      X   12.0
1       A      Y   20.0
2       A      Z    5.0
3       B      X   10.0
4       B      Y    5.0
5       C      Z    7.0
6       C      X    2.0
Related