1

I have a pandas DataFrame df which looks like

    State_N    State     REL1506   REL 1512   REL1606 ...
0   3018       state1    0.0103    0.0102     0.0099
1   3026       state2    0.0179    0.0171     0.0161
2   3034       state3    0.0222    0.0201     0.0189
...

and I would like to reshape it so that I can then use it for an animated choropleth map of the states with each "year" of the animation being each REL column. If I understand it correctly I need a shape like this.

    State_N    State     REL_VAL   REL
0   3018       state1    0.0103    REL1506 ...
1   3026       state2    0.0179    REL1506
2   3034       state3    0.0222    REL1506
3   3018       state1    0.0102    REL1512
4   3026       state2    0.0171    REL1512
5   3034       state3    0.0201    REL1512
6   3018       state1    0.0099    REL1606
7   3026       state2    0.0161    REL1606
8   3034       state3    0.0189    REL1606
...

The only way that I can come up with right now would be if I created a dataframe of State_N State RELxxxx for each REL column and then concat them but I feel like there has to be a better way. Any ideas?

SOLUTION

Use df.melt(['State_N','State'])

brownie
  • 121
  • 9
  • Dup: https://stackoverflow.com/questions/23354124/how-can-i-unpivot-specific-columns-from-a-pandas-dataframe – Corralien Feb 13 '22 at 16:57

0 Answers0