HappyPy
HappyPy

Reputation: 10697

create correlation-matrix-like data frame in pandas

I have a df with correlation values for A and B

df = pd.DataFrame({'x':['A','A','B','B'],'y':['A','B','A','B'],'c':[1,0.5,0.5,1]})

I'm trying to create a correlation-matrix-like data frame from df of the kind DataFrame.corr would give me. I tried

corr = df.pivot_table(columns='y',index='x')
y    A    B
x          
A  1.0  0.5
B  0.5  1.0

but I don't know how to get rid of the multi-index.

Upvotes: 3

Views: 182

Answers (1)

Andy L.
Andy L.

Reputation: 25269

You just need specifying values to get rid of multiindex

corr = df.pivot_table(columns='y',index='x', values='c')

Out[41]:
y    A    B
x
A  1.0  0.5
B  0.5  1.0

If you also want to get rid of axis name, chain rename_axis

corr = (df.pivot_table(columns='y',index='x', values='c')
          .rename_axis(index=None, columns=None))

Out[43]:
     A    B
A  1.0  0.5
B  0.5  1.0

Upvotes: 3

Related Questions