尝试从Pandas Dataframe创建Seaborn热图

时间:2018-04-24 18:22:58

标签: pandas python-3.6 heatmap seaborn

这是第一次尝试这个。我实际上有一个我在程序中生成的列表的字典,但由于这是我第一次尝试这个,我使用的是一个虚拟的dict只是为了测试。

我跟着这个: python Making heatmap from DataFrame

但我失败了以下内容:

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 20, in <module>
    sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)
  File "C:\Users\Mark\AppData\Roaming\Python\Python36\site-packages\seaborn\matrix.py", line 517, in heatmap
    yticklabels, mask)
  File "C:\Users\Mark\AppData\Roaming\Python\Python36\site-packages\seaborn\matrix.py", line 168, in __init__
    cmap, center, robust)
  File "C:\Users\Mark\AppData\Roaming\Python\Python36\site-packages\seaborn\matrix.py", line 205, in _determine_cmap_params
    calc_data = plot_data.data[~np.isnan(plot_data.data)]
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我的代码:

import pandas as pd
import seaborn as sns


Index = ['key1', 'key2', 'key3', 'key4', 'key5']
Cols = ['A', 'B', 'C', 'D']

testdict = {
    "key1": [1, 2, 3, 4],
    "key2": [5, 6, 7, 8],
    "key3": [9, 10, 11, 12],
    "key4": [13, 14, 15, 16],
    "key5": [17, 18, 19, 20]
}

df = pd.DataFrame(testdict, index=Index, columns=Cols)
df = df.transpose()

sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

1 个答案:

答案 0 :(得分:0)

您需要切换列和索引标签

Cols = ['key1', 'key2', 'key3', 'key4', 'key5']
Index = ['A', 'B', 'C', 'D']