1

In python and pandas I have a dataframe that I need to turn into tidy data to make charts easier

The original data is like this:

enter image description here

I want to transform into a dataframe, with the transposition of the data and adapting column names:

enter image description here

Please is there a way in python to do this?

Reinaldo Chaves
  • 965
  • 4
  • 16
  • 43

1 Answers1

2

Use melt:

out = df.melt('year', var_name='localization', value_name='number_of_tests')

You can also use:

out = df.set_index('year').rename_axis(columns='localization').unstack() \
        .rename('number_of_tests').reset_index()
Corralien
  • 109,409
  • 8
  • 28
  • 52