将相关矩阵转换为大 pandas 中的3列数据框? [英] Transforming a correlation matrix to a 3 column dataframe in pandas?

查看:62
本文介绍了将相关矩阵转换为大 pandas 中的3列数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的相关矩阵

I have a correlation matrix like so

    a     b   c
  a 1    0.5  0.3
  b 0.5   1   0.7
  c 0.3  0.7  1

我想将其转换成数据列,其中的列是这样的:

And I want to transform this into a dataframe where the columns are like this:

Letter1   letter2   correlation
   a        a           1
   a        b           0.5
   a        c           0.3
   b        a           0.5
   b        b            1      
   .        .            .
   .        .            .      

是否有熊猫命令允许我执行此操作?预先感谢

Is there a pandas command to allow me to do this? Thanks in advance

接下来,我可以像这样为Letter1中的字母分配一个值:

And a follow up to this, can I assign a value to the letters in Letter1 like so:

 Value1 Letter1  Value2 letter2   correlation
  1        a       1      a           1
  1        a       2      b           0.5
  1        a       3      c           0.3
  2        b       1      a           0.5
  2        b       2      b            1      
  .        .       .      .            .
  .        .       .      .            .   

推荐答案

使用 stack 重置索引 :

df1 = df.stack().reset_index()
df1.columns = ['Letter1','Letter2','correlation']
print (df1)
  Letter1 Letter2  correlation
0       a       a          1.0
1       a       b          0.5
2       a       c          0.3
3       b       a          0.5
4       b       b          1.0
5       b       c          0.7
6       c       a          0.3
7       c       b          0.7
8       c       c          1.0

然后 插入 列,按 factorize填充的位置 值:

df1.insert(0, 'Value1', pd.factorize(df1['Letter1'])[0] + 1)
df1.insert(2, 'Value2', pd.factorize(df1['Letter2'])[0] + 1)

print (df1)
   Value1 Letter1  Value2 Letter2  correlation
0       1       a       1       a          1.0
1       1       a       2       b          0.5
2       1       a       3       c          0.3
3       2       b       1       a          0.5
4       2       b       2       b          1.0
5       2       b       3       c          0.7
6       3       c       1       a          0.3
7       3       c       2       b          0.7
8       3       c       3       c          1.0

这篇关于将相关矩阵转换为大 pandas 中的3列数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆