如何将 pandas 数据框转换为热图兼容数据框?

How to transform a pandas dataframe into a heatmap compatible dataframe?

我有一个 pandas 数据框,看起来像这样:

  x_specie   y_species         r_value        irrelevant 
0    name1    name2    0.46042854769889    1.08625581318480
1    name3    name4    0.08520026289205    0.31828185948920
2    name5    name6    0.59751876928376    0.03611201620948
3    name7    name8    0.21827455728522    1.28464913995526
4    name9    name10    0.03241820474363    0.69957843027741

可以用以下方法生成类似的东西:

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

本质上,我想使用 matplotlibs ax.pcolor() 制作 r_value 列的热图,但我需要首先将这些数据转换为适当的格式,我认为是这样的:

     name2     name4     name6    name8    name10
name1 r_value1 ...       ...               ...
name3 ...      ...
name5                    ...
name7                             ...
name9 ...                                  ...

将 r_value 填充到正确的位置 table(请注意,尽管上面的虚拟数据并未涵盖我的实际数据所涵盖的所有潜在组合)。

最简单的方法是什么?提前致谢

您可以使用 pivot_table and fillna 来获得 x 和 y 物种的所有组合(用 0 填充 NaN)。

import matplotlib.pyplot as plt
import pandas as pd

pivoted_table = df.pivot(index='x_specie', columns='y_species', values='r_value')
pivoted_table.fillna(0, inplace=True)
plt.pcolor(pivoted_table.values, cmap=plt.cm.Reds)
plt.show()