0

I have a data frame with 4 columns and I want to pivot it the following way:

ORIGINAL TABLE:

RA T V ES
01 ee 0 AA
01 dd -1 AA
01 hh 9 AA
02 ee 0 AA
02 dd 8 AA
02 hh -2 AA
03 ee 5 BB
03 dd 3 BB
03 hh 4 BB
04 ee -7 CC
04 dd 2 CC
04 hh 0 CC

DESIRED TABLE AFTER PIVOTING:

RA ee dd hh ES
01 0 -1 9 AA
02 0 8 -2 AA
03 5 3 4 BB
04 -7 2 0 CC

In the past I pivot a table with 3 columns and it worked just fine. This time, I want

RA to be the index

T to be the columns

V to be the values

ES to keep as is (as described above).

I would really appreciate any help.

Thanks!

Rabinzel
  • 7,757
  • 3
  • 10
  • 30
Eli
  • 23
  • 5
  • Use `index=['RA','ES']` – jezrael Oct 20 '22 at 09:45
  • @jezraels input plus after pivoting use `.reset_index(level='ES')` – Rabinzel Oct 20 '22 at 09:46
  • @jezrael Will it work even though 'ES' is not unique in the pivoted table? – Eli Oct 20 '22 at 09:47
  • @Rabinzel - When I try "RA" as index it works but "ES" doesn't appear in the pivoted table. However, when I try "ES" as index or ["RA", "ES"] as index it fails.. – Eli Oct 20 '22 at 11:25
  • @Eli based on your provided example I used this line and got your desired output: `df.pivot(index=['RA', 'ES'], columns='T', values='V').reset_index(level='ES')`. Did you try it like this and it failed? What error message did you get? – Rabinzel Oct 20 '22 at 12:32

0 Answers0