【问题标题】:Sorting correlation matrix排序相关矩阵
【发布时间】:2022-08-17 08:43:46
【问题描述】:

我想将相关矩阵转换为“pandas”表,从最大值到最小值排序,如图所示。我该怎么做?

df = pd.DataFrame(np.random.randint(0,15,size=(20, 6)), columns=[\"Ply_1\",\"Ply_2\",\"Ply_3\",\"Ply_4\",\"Ply_5\",\"Ply_6\"])
df[\'date\'] = pd.date_range(\'2000-1-1\', periods=20, freq=\'D\')
df = df.set_index([\'date\'])
cor=df.corr()
print(cor)

Out image link here

标签: python pandas sorting correlation


【解决方案1】:
pd.concat([cor[col_name].sort_values(ascending=False)
                        .rename_axis(col_name.replace('Ply', 'index'))
                        .reset_index() 
           for col_name in cor], 
          axis=1)

解释:

  • pd.concat([df_1, ..., df_6], axis=1) 连接 6 个数据帧(每个数据帧都已经排序,并且有 2 列:“index_i”和“Ply_i”)。

  • [cor[col_name] for col_name in cor] 将创建一个包含 6 个系列的列表,其中每个系列是 cor 的下一列。

  • ser.sort_values(ascending=False) 按降序对系列 ser 的值进行排序(索引也会移动 - 连同它们的值一起移动)。

  • col_name.replace('Ply', 'index') 通过将 'Ply' 替换为 'index' 从字符串 col_name 创建一个新字符串。

  • ser.rename_axis(name).reset_index() 重命名索引轴,并将索引(及其名称)提取为新列,将 Series 转换为 DataFrame。此数据帧的新索引是默认范围索引(从 0 到 6)。

结果:

(用我随机生成的数字)

index_1 Ply_1 index_2 Ply_2 index_3 Ply_3 index_4 Ply_4 index_5 Ply_5 index_6 Ply_6
0 Ply_1 1 Ply_2 1 Ply_3 1 Ply_4 1 Ply_5 1 Ply_6 1
1 Ply_2 0.387854 Ply_1 0.387854 Ply_1 0.258825 Ply_1 0.337613 Ply_4 0.0618012 Ply_1 0.058282
2 Ply_4 0.337613 Ply_4 0.293496 Ply_4 0.0552454 Ply_2 0.293496 Ply_2 0.060881 Ply_3 -0.207621
3 Ply_3 0.258825 Ply_5 0.060881 Ply_2 -0.0900126 Ply_5 0.0618012 Ply_3 -0.110885 Ply_2 -0.22012
4 Ply_6 0.058282 Ply_3 -0.0900126 Ply_5 -0.110885 Ply_3 0.0552454 Ply_1 -0.390893 Ply_4 -0.291842
5 Ply_5 -0.390893 Ply_6 -0.22012 Ply_6 -0.207621 Ply_6 -0.291842 Ply_6 -0.394074 Ply_5 -0.394074

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 2023-01-27
    • 2020-01-11
    • 2017-12-18
    • 2012-11-04
    • 2022-12-22
    • 1970-01-01
    • 2014-02-19
    相关资源
    最近更新 更多