Pandas Convert Multiple Columns to Rows

Viewed 53

I have a pandas dataframe as follows:

     code    title      amount_1  amount_2   currency_1    currency_2
0     246       ex           500       550          USD           GBP
1     300       am           200       250          USD           GBP
2     315      ple           300       325          USD           GBP

I'd like to get this into the format

code    title   amount   currency
246        ex      500        USD
246        ex      550        GBP

All of the currencies are the same. How can I get this format? I've tried using melt and reset_index, but neither seemed to do exactly what I need. Thank you

1 Answers

Use wide_to_long:

df1 = pd.wide_to_long(df, 
                      stubnames=['amount','currency'], 
                      i=['code','title'], 
                      j='measure', sep='_').reset_index()

print (df1)
   code title  measure  amount currency
0   246    ex        1     500      USD
1   246    ex        2     550      GBP
2   300    am        1     200      USD
3   300    am        2     250      GBP
4   315   ple        1     300      USD
5   315   ple        2     325      GBP
Related