-1

Considering the following dataframe:

import pandas as pd
import numpy as np
import random
np.random.seed(10)

df1 = pd.DataFrame({'x':[1,2,3,4,5,1,2,3,4,5],
              'y':[10,10,10,10,10,20,20,20,20,20],
              'z':np.random.normal(size = 10)
              })

I want to convert the x values into columns and y values into index (decreasing) with corresponding z values in the dataframe. It's something like this df2:

df2 = pd.DataFrame(np.random.randn(2,5), index = [20,10], columns=[1,2,3,4,5])

How can I conver df1 into df2's style?

YQ.Wang
  • 1,090
  • 1
  • 17
  • 43

1 Answers1

0

You can use pandas.pivot_table:

res = df1.pivot_table(index='y', columns='x', values='z')

You may wish to remove or change your index names, but this is your result:

x          1         2         3         4         5
y                                                   
10  1.331587  0.715279 -1.545400 -0.008384  0.621336
20 -0.720086  0.265512  0.108549  0.004291 -0.174600
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Can I have the index to be decreased `y`? From 20 at first row to 10 at second row in this case. – YQ.Wang May 14 '18 at 14:52
  • @YQ.Wang, I'm sure that's possible. You can look up how to sort indices in pandas. Something like `.sort_index(ascending=False)` might work. – jpp May 14 '18 at 14:55