Data restructuring from column wise to row wise

Viewed 33

so during an interview I was challenged with a problem that I couldn't seem to figure out on dataset restructuring that I was hoping that someone could give me some guidance to!

Original:

Original format

Final:

enter image description here

The data is made up and is a simplified version of what was asked but the principle that I couldn't figure out is essentially the same.

Thank you! I really appreciate the help!

1 Answers

Use DataFram.pivot:

new_df = df.pivot(index='state', columns='metric', values='values').reset_index().rename_axis(None, axis=1)

Output:

>>> new_df
   state  gender ratio  population  temperature
0  texas          0.45      5000.0         60.0
Related