1

I need helo creating the format transformation:

See here

I have created pd.wide_to_long but I cannot find an example identical to mine?

Can you help?

Community
  • 1
  • 1
Modvinden
  • 33
  • 2
  • 8

1 Answers1

1

Use:

df.set_index(['City','Var']).rename_axis(columns='Year').stack().unstack('Var')
ansev
  • 30,322
  • 5
  • 17
  • 31
  • Thank you. I get the error: "ValueError: Index contains duplicate entries, cannot reshape" Can you help? – Modvinden Mar 16 '20 at 21:39
  • could you copy and paste your dataframe? I need it to make a solution – ansev Mar 16 '20 at 21:40
  • https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples I need it to copy with `pd.read_clipboard` – ansev Mar 16 '20 at 21:41
  • You could copy an paste a example – ansev Mar 16 '20 at 21:42
  • There were dublicates in the ID - so that ex. all cities had var 1 twice. You code worked! However, when I run your code, some var disapear for some cities. Ex City A is missing Var 1 but not any other cities. Do you know why? – Modvinden Mar 16 '20 at 21:58
  • I should run it to know maybe you need sort with `DataFrame.sort_values` – ansev Mar 16 '20 at 22:00
  • The solution: df.set_index(['City','Var']).rename_axis(columns='Year').stack(dropna = False).unstack('Var') – Modvinden Mar 16 '20 at 22:02