0

I have a list of (x,y,z) tuples in a dataframe A. How can I produce a dataframe B which represents the underlying matrix of A, using the existing values of x and y as index and columns values, respectively?

Example:

A:

x y z
1 1 1 
1 2 10
2 1 100

B:

    1    2
1   1    10
2   100  NaN
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Nilo Araujo
  • 725
  • 6
  • 15
  • What is `print(A.info())` ? Because if `x,y,z` are columns then need [pivot](https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe) – jezrael Jan 13 '18 at 16:35

1 Answers1

1

For this data frame df:

   x  y    z
0  1  1    1
1  1  2   10
2  2  1  100

pivoting:

df.pivot(index='x', columns='y')

works:

       z      
y      1     2
x             
1    1.0  10.0
2  100.0   NaN

You can also clean the column and index names:

res = df.pivot(index='x', columns='y')
res.index.name = None
res.columns = res.columns.levels[1].values
print(res)

Output:

       1     2
1    1.0  10.0
2  100.0   NaN
Mike Müller
  • 82,630
  • 20
  • 166
  • 161