Pandas long to wide reshape, by two variables

Here’s another solution more fleshed out, taken from Chris Albon’s site.

Create “long” dataframe

raw_data = {'patient': [1, 1, 1, 2, 2],
                'obs': [1, 2, 3, 1, 2],
          'treatment': [0, 1, 0, 1, 0],
              'score': [6252, 24243, 2345, 2342, 23525]}

df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])

Make a “wide” data

df.pivot(index='patient', columns="obs", values="score")

Leave a Comment